查看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 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