mongodb命令行操作

查看mongo命令帮助

sitewhere-mongodb-primary-0:/$ mongo --help
MongoDB shell version v4.0.3
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
  foo                   foo database on local machine
  192.168.0.5/foo       foo database on 192.168.0.5 machine
  192.168.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
Options:
  --shell                             run the shell after executing files
  --nodb                              don't connect to mongod on startup - no 
                                      'db address' arg expected
  --norc                              will not run the ".mongorc.js" file on 
                                      start up
  --quiet                             be less chatty
  --port arg                          port to connect to
  --host arg                          server to connect to
  --eval arg                          evaluate javascript
  -h [ --help ]                       show this usage information
  --version                           show version information
  --verbose                           increase verbosity
  --ipv6                              enable IPv6 support (disabled by default)
  --disableJavaScriptJIT              disable the Javascript Just In Time 
                                      compiler
  --enableJavaScriptJIT               enable the Javascript Just In Time 
                                      compiler
  --disableJavaScriptProtection       allow automatic JavaScript function 
                                      marshalling
  --ssl                               use SSL for all connections
  --sslCAFile arg                     Certificate Authority file for SSL
  --sslPEMKeyFile arg                 PEM certificate/key file for SSL
  --sslPEMKeyPassword arg             password for key in PEM file for SSL
  --sslCRLFile arg                    Certificate Revocation List file for SSL
  --sslAllowInvalidHostnames          allow connections to servers with 
                                      non-matching hostnames
  --sslAllowInvalidCertificates       allow connections to servers with invalid
                                      certificates
  --sslFIPSMode                       activate FIPS 140-2 mode at startup
  --sslDisabledProtocols arg          Comma separated list of TLS protocols to 
                                      disable [TLS1_0,TLS1_1,TLS1_2]
  --retryWrites                       automatically retry write operations upon
                                      transient network errors
  --disableImplicitSessions           do not automatically create and use 
                                      implicit sessions
  --jsHeapLimitMB arg                 set the js scope's heap size limit

Authentication Options:
  -u [ --username ] arg               username for authentication
  -p [ --password ] arg               password for authentication
  --authenticationDatabase arg        user source (defaults to dbname)
  --authenticationMechanism arg       authentication mechanism
  --gssapiServiceName arg (=mongodb)  Service name to use when authenticating 
                                      using GSSAPI/Kerberos
  --gssapiHostName arg                Remote host name to use for purpose of 
                                      GSSAPI/Kerberos authentication

 

连接数据库

sitewhere-mongodb-primary-0:/$ mongo -u username -p password
MongoDB shell version v4.0.3

 

查看帮助

rs0:PRIMARY> help
    db.help()                    help on db methods
    db.mycoll.help()             help on collection methods
    sh.help()                    sharding helpers
    rs.help()                    replica set helpers
    help admin                   administrative help
    help connect                 connecting to a db help
    help keys                    key shortcuts
    help misc                    misc things to know
    help mr                      mapreduce

    show dbs                     show database names
    show collections             show collections in current database
    show users                   show users in current database
    show profile                 show most recent system.profile entries with time >= 1ms
    show logs                    show the accessible logger names
    show log [name]              prints out the last segment of log in memory, 'global' is default
    use <db_name>                set current database
    db.foo.find()                list objects in collection foo
    db.foo.find( { a : 1 } )     list objects in foo where a == 1
    it                           result of the last line evaluated; use to further iterate
    DBQuery.shellBatchSize = x   set default number of items to display on shell
    exit                         quit the mongo shell

 

查看库

rs0:PRIMARY> show dbs;
admin           0.000GB
config          0.000GB
local           0.001GB
tenant-default  0.000GB

 

创建/切换数据库: use dancy , dancy是数据库名称
如果use后面的数据库存在则切换到该数据库,如果不存在则创建。

rs0:PRIMARY> use tenant-default;
switched to db tenant-default

 

查看当前所在数据库

rs0:PRIMARY> db
tenant-default

 

查看当前库有多少个集合

rs0:PRIMARY> show collections
assets
assettypes
devicestates
events
scheduledjobs
schedules

 

查询某个集合的内容

rs0:PRIMARY> db.assets.find()
{ "_id" : BinData(3,"YE2/smBotc1ZqEhMNcL2nA=="), "atid" : BinData(3,"FkP4uECSQu3w2PBgMGlfsA=="), "name" : "Derek Adams", "imgu" : "https://s3.amazonaws.com/sitewhere-demo/people/derek.jpg", "icon" : null, "bgco" : null, "fgco" : null, "bdco" : null, "tokn" : "derek.adams@sitewhere.com", "crdt" : ISODate("2020-01-07T09:02:54.510Z"), "meta" : { "role" : "dev", "phone" : "678-555-1212", "username" : "derek" } }
{ "_id" : BinData(3,"J0LV83h9RGGwjZDWnRwdrw=="), "atid" : BinData(3,"FkP4uECSQu3w2PBgMGlfsA=="), "name" : "Bryan Rank", "imgu" : "https://s3.amazonaws.com/sitewhere-demo/people/bryan.jpg", "icon" : null, "bgco" : null, "fgco" : null, "bdco" : null, "tokn" : "bryan.rank@sitewhere.com", "crdt" : ISODate("2020-01-07T09:02:54.518Z"), "meta" : { "role" : "sales", "phone" : "770-555-1212", "username" : "bryan" } }
{ "_id" : BinData(3,"601iYuo9PWETKfQgGVwXtw=="), "atid" : BinData(3,"FkP4uECSQu3w2PBgMGlfsA=="), "name" : "Martin Weber", "imgu" : "https://s3.amazonaws.com/sitewhere-demo/people/martin.jpg", "icon" : null, "bgco" : null, "fgco" : null, "bdco" : null, "tokn" : "martin.weber@sitewhere.com", "crdt" : ISODate("2020-01-07T09:02:54.520Z"), "meta" : { "role" : "busdev", "phone" : "404-555-1212", "username" : "martin" } }

 

db用法
db.2个Tab键

rs0:PRIMARY> db.
db.adminCommand(               db.dbEval(                     db.getFreeMonitoringStatus(    db.getSiblingDB(               db.isMaster(                   db.revokePrivilegesFromRole(   db.stats(
db.aggregate(                  db.disableFreeMonitoring(      db.getLastError(               db.getSisterDB(                db.killOP(                     db.revokeRolesFromRole(        db.toLocaleString
db.auth(                       db.dropAllRoles(               db.getLastErrorCmd(            db.getSlaveOk(                 db.killOp(                     db.revokeRolesFromUser(        db.toString(
db.changeUserPassword(         db.dropAllUsers(               db.getLastErrorObj(            db.getUser(                    db.listCommands(               db.runCommand(                 db.tojson(
db.cloneCollection(            db.dropDatabase(               db.getLogComponents(           db.getUsers(                   db.loadServerScripts(          db.runCommandWithMetadata(     db.unsetWriteConcern(
db.cloneDatabase(              db.dropRole(                   db.getMongo(                   db.getWriteConcern(            db.logout(                     db.runReadCommand(             db.updateRole(
db.commandHelp(                db.dropUser(                   db.getName(                    db.grantPrivilegesToRole(      db.printCollectionStats(       db.serverBits(                 db.updateUser(
db.constructor                 db.enableFreeMonitoring(       db.getPrevError(               db.grantRolesToRole(           db.printReplicationInfo(       db.serverBuildInfo(            db.valueOf
db.copyDatabase(               db.eval(                       db.getProfilingLevel(          db.grantRolesToUser(           db.printShardingStatus(        db.serverCmdLineOpts(          db.version(
db.createCollection(           db.forceError(                 db.getProfilingStatus(         db.group(                      db.printSlaveReplicationInfo(  db.serverStatus(
db.createRole(                 db.fsyncLock(                  db.getQueryOptions(            db.groupcmd(                   db.propertyIsEnumerable        db.setLogLevel(
db.createUser(                 db.fsyncUnlock(                db.getReplicationInfo(         db.groupeval(                  db.prototype                   db.setProfilingLevel(
db.createView(                 db.getCollection(              db.getRole(                    db.hasOwnProperty              db.removeUser(                 db.setSlaveOk(
db.currentOP(                  db.getCollectionInfos(         db.getRoles(                   db.help(                       db.repairDatabase(             db.setWriteConcern(
db.currentOp(                  db.getCollectionNames(         db.getSession(                 db.hostInfo(                   db.resetError(                 db.shutdownServer(

 

创建数据库

rs0:PRIMARY> use dancy
switched to db dancy

 


往里面插入数据show dbs才能显示到

rs0:PRIMARY> db.jihe.insert({"name": "lin"})
WriteResult({ "nInserted" : 1 })
rs0:PRIMARY> show dbs
admin           0.000GB
config          0.000GB
dancy           0.000GB
local           0.001GB
tenant-default  0.000GB
rs0:PRIMARY> show collections
jihe
rs0:PRIMARY> db.jihe.find()
{ "_id" : ObjectId("5e16b3a7ab5fc9b3b213226b"), "name" : "lin" }

 


删除集合

rs0:PRIMARY> db.jihe.drop()
true

 

插入文档,user是集合名称

rs0:PRIMARY> db.user.insert({"name": "lin", "age": 23})
WriteResult({ "nInserted" : 1 })
rs0:PRIMARY> show collections
jihe
user

 

删除当前所在数据库

rs0:PRIMARY> db.dropDatabase()
{
    "dropped" : "dancy",
    "ok" : 1,
    "operationTime" : Timestamp(1578546278, 2),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1578546278, 2),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    }
}
rs0:PRIMARY> show dbs;
admin           0.000GB
config          0.000GB
local           0.001GB
tenant-default  0.000GB
posted @ 2020-01-09 13:38  linyouyi  阅读(3273)  评论(0编辑  收藏  举报