MongoDB 数据库客户端命令--mongo

命令mongo 可以与数据库建立连接并操作数据库。

${MongoDB_HOME}/bin目录下执行:
 ./mongo --help

MongoDB shell version v3.4.0
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
  --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
  --networkMessageCompressors arg     Comma-separated list of compressors to 
                                      use for network messages
  --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

file names: a list of files to run. files have to end in .js and will exit after unless 
--shell is specified

  简单示例:

 ./mongo 127.0.0.1:27017/local

   连接本机端口27017上的mongdb数据库,并打开local数据库。

 ./mongo 127.0.0.1:27017 
>use mydb //打开数据库,如果不存在该数据库则新建一个并打开数据库
switched to db mydb
>show dbs //显示数据库
admin
local //由于mydb 新建的数据库,无数据,所不未显示
>db //查看当前数据库
mydb
>show collections //查看当前库下所有集合
> //, 新建库无集合,所以未显示
>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
>db.help() 显示数据库支持的函数
DB methods:
        db.adminCommand(nameOrDocument) - switches to 'admin' db, 
                  and runs command [ just calls db.runCommand(...) ]
        db.auth(username, password)
        db.cloneDatabase(fromhost)
        db.commandHelp(name) returns the help for the command
        db.copyDatabase(fromdb, todb, fromhost)
        db.createCollection(name, { size : ..., capped : ..., max : ... } )
        db.createView(name, viewOn, [ { $operator: {...}}, ... ], { viewOptions } )
        db.createUser(userDocument)
        db.currentOp() displays currently executing operations in the db
        db.dropDatabase()
        db.eval() - deprecated
        db.fsyncLock() flush data to disk and lock server for backups
        db.fsyncUnlock() unlocks server following a db.fsyncLock()
        db.getCollection(cname) same as db['cname'] or db.cname
        db.getCollectionInfos([filter]) - returns a list that 
             contains the names and options of the db's collections
        db.getCollectionNames()
        db.getLastError() - just returns the err msg string
        db.getLastErrorObj() - return full status object
        db.getLogComponents()
        db.getMongo() get the server connection object
        db.getMongo().setSlaveOk() allow queries on a 
            replication slave server
        db.getName()
        db.getPrevError()
        db.getProfilingLevel() - deprecated
        db.getProfilingStatus() - returns if profiling is on and slow threshold
        db.getReplicationInfo()
        db.getSiblingDB(name) get the db at the same server as this one
        db.getWriteConcern() - returns the write concern 
            used for any operations on this db, inherited from server object if set
        db.hostInfo() get details about the server's host
        db.isMaster() check replica primary status
        db.killOp(opid) kills the current operation in the db
        db.listCommands() lists all the db commands
        db.loadServerScripts() loads all the scripts in db.system.js
        db.logout()
        db.printCollectionStats()
        db.printReplicationInfo()
        db.printShardingStatus()
        db.printSlaveReplicationInfo()
        db.dropUser(username)
        db.repairDatabase()
        db.resetError()
        db.runCommand(cmdObj) run a database command. 
              if cmdObj is a string, turns it into { cmdObj : 1 }
        db.serverStatus()
        db.setLogLevel(level,<component>)
        db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
        db.setWriteConcern( <write concern doc> ) - 
             sets the write concern for writes to the db
        db.unsetWriteConcern( <write concern doc> ) - 
               unsets the write concern for writes to the db
        db.setVerboseShell(flag) display extra information in shell output
        db.shutdownServer()
        db.stats()
        db.version() current version of the server
		
		
>db.mycollection.help()//显示集合的支持的操作 mycoll为集合的名字
DBCollection help
        db.mycollection.find().help() - show DBCursor help
        db.mycollection.bulkWrite( operations, <optional params> )
                   - bulk execute write operations, 
                   optional parameters are: w, wtimeout, j
        db.mycollection.count( query = {}, <optional params> ) 
                   - count the number of documents that matches the 
                   query, optional parameters are: limit, skip, hint,maxTimeMS
        db.mycollection.copyTo(newColl) - duplicates collection by c
                 opying all documents to newColl; no indexes are copied.
        db.mycollection.convertToCapped(maxBytes) - calls 
               {convertToCapped:'user', size:maxBytes}} command
        db.mycollection.createIndex(keypattern[,options])
        db.mycollection.createIndexes([keypatterns], <options>)
        db.mycollection.dataSize()
        db.mycollection.deleteOne( filter, <optional params> ) 
              - delete first matching document, optional parameters are: w, wtimeout, j
        db.mycollection.deleteMany( filter, <optional params> ) 
               - delete all matching documents, optional parameters are: w, wtimeout, j
        db.mycollection.distinct( key, query, <optional params> ) 
             - e.g. db.mycollection.distinct( 'x' ), optional parameters are: maxTimeMS
        db.mycollection.drop() drop the collection
        db.mycollection.dropIndex(index) 
               - e.g.  db.mycollection.dropIndex( "indexName" ) or 
                       db.mycollection.dropIndex( { "indexKey" : 1 } )
        db.mycollection.dropIndexes()
        db.mycollection.ensureIndex(keypattern[,options]) - DEPRECATED, 
                 usecreateIndex() instead
        db.mycollection.explain().help() - show explain help
        db.mycollection.reIndex()
        db.mycollection.find([query],[fields]) - query is an 
              optional query filter.fields is optional set of fields to return.
               e.g. db.mycollection.find({x:77} , {name:1, x:1} )
        db.mycollection.find(...).count()
        db.mycollection.find(...).limit(n)
        db.mycollection.find(...).skip(n)
        db.mycollection.find(...).sort(...)
        db.mycollection.findOne([query], [fields], [options], [readConcern])
        db.mycollection.findOneAndDelete( filter, <optional params> )
              - delete first matching document, optional parameters are
              : projection, sort, maxTimeMS
        db.mycollection.findOneAndReplace( filter, replacement, 
              <optional params> ) -replace first matching document, 
             optional parameters are: projection, sort,maxTimeMS, upsert,
              returnNewDocument
        db.mycollection.findOneAndUpdate( filter, update, <optional params> )
              - updatefirst matching document, optional parameters are:
                 projection, sort, maxTimeMS,upsert, returnNewDocument
        db.mycollection.getDB() get DB object associated with collection
        db.mycollection.getPlanCache() get query plan cache 
                associated with collection
        db.mycollection.getIndexes()
        db.mycollection.group( { key : ..., initial: ..., reduce : ...[, cond: ...] })
        db.mycollection.insert(obj)
        db.mycollection.insertOne( obj, <optional params> ) 
                - insert a document,optional parameters are: w, wtimeout, j
        db.mycollection.insertMany( [objects], <optional params> ) 
                  - insert multipledocuments, optional parameters are: w, wtimeout, j
        db.mycollection.mapReduce( mapFunction , reduceFunction , <optional params> )
        db.mycollection.aggregate( [pipeline], <optional params> )
                 - performs anaggregation on a collection; returns a cursor
        db.mycollection.remove(query)
        db.mycollection.replaceOne( filter, replacement, <optional params> ) 
                - replacethe first matching document, optional parameters are: 
                      upsert, w, wtimeout, j
        db.mycollection.renameCollection( newName , <dropTarget> ) renames thecollection.
        db.mycollection.runCommand( name , <options> ) runs a db
                    command with thegiven name where the 
                    first param is the collection name
        db.mycollection.save(obj)
        db.mycollection.stats({scale: N, indexDetails: true/false, 
                  indexDetailsKey:<index key>, index DetailsName: <index name>})
        db.mycollection.storageSize() - includes free space allocated to this collection
        db.mycollection.totalIndexSize() - size in bytes of all the indexes
        db.mycollection.totalSize() - storage allocated for all data and indexes
        db.mycollection.update( query, object[, upsert_bool, multi_bool] ) 
                  - instead of two flags, you can pass an object 
                     with fields: upsert, multi
        db.mycollection.updateOne( filter, update, <optional params> )
                - update the first matching document, optional parameters are: 
                 upsert, w, wtimeout, j
        db.mycollection.updateMany( filter, update, <optional params> ) 
                - update all matching documents, optional parameters are: 
                   upsert, w, wtimeout, j
        db.mycollection.validate( <full> ) - SLOW
        db.mycollection.getShardVersion() - only for use with sharding
        db.mycollection.getShardDistribution() - prints statistics
                    about data distribution in the cluster
        db.mycollection.getSplitKeysForChunks( <maxChunkSize> )
                   - calculates split points over all 
                    chunks and returns splitter function
        db.mycollection.getWriteConcern() - returns the write 
                concern used for any operations on this collection, 
              inherited from server/db if set
        db.mycollection.setWriteConcern( <write concern doc> )
                - sets the write concern for writes to the collection
        db.mycollection.unsetWriteConcern( <write concern doc> )
                  - unsets the write concern for writes to the collection
        db.mycollection.latencyStats() 
                 - display operation latency histograms for this collection

猜你喜欢

转载自java12345678.iteye.com/blog/2344157