Mongo shell 的帮助命令 (二)

来源:互联网 发布:node throw err 编辑:程序博客网 时间:2024/05/01 15:40

大家应该都有使用过命令行去做一些操作,尤其是 linux 的一些命令,繁琐又难记,本人曾尝试的去背一些linux 命令,但是基本过了几天不用差不多就忘记了,而且还有茫茫多的参数,所以到现在都是用到的时候去百度一下(不太习惯看linux的help,感觉不好理解,可能没有仔细的去看吧)。最近看 mongo 的文档,感觉mongo本身提供的方法帮助文档真的挺简单的,最起码看方法名能知道这个方法是干嘛的,学习mongo的可以尝试着这些命令去熟悉下mongo提供的方法。唉,总喜欢罗哩罗嗦说一大堆没用的。

 由于 mongo 是个 javascript shell ,通过在线查看 javascript 的文档能够得到很多帮助,shell 本身内置了帮助文档,可以通过 help 命令查看。

> 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

下面列举了几个命令,可以自己去命令行执行下这些命令,看看都有哪些方法。

1. db.help()           help on db methods

> db.help();
DB methods:
        db.addUser(username, password[, readOnly=false])
        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.currentOp() displays currently executing operations in the db
        db.dropDatabase()
        db.eval(func, args) run code server-side
        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.getCollectionNames()
        db.getLastError() - just returns the err msg string
        db.getLastErrorObj() - return full status object
        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.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.removeUser(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.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
        db.setVerboseShell(flag) display extra information in shell output
        db.shutdownServer()
        db.stats()
        db.version() current version of the server

2. db.mycoll.help()             help on collection methods

> db.mycoll.help()
DBCollection help
        db.mycoll.find().help() - show DBCursor help
        db.mycoll.count()
        db.mycoll.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
        db.mycoll.convertToCapped(maxBytes) - calls {convertToCapped:'mycoll', size:maxBytes}} command
        db.mycoll.dataSize()
        db.mycoll.distinct( key ) - e.g. db.mycoll.distinct( 'x' )
        db.mycoll.drop() drop the collection
        db.mycoll.dropIndex(index) - e.g. db.mycoll.dropIndex( "indexName" ) or db.mycoll.dropIndex( { "indexKey" : 1 } )
        db.mycoll.dropIndexes()
        db.mycoll.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
        db.mycoll.reIndex()
        db.mycoll.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                      e.g. db.mycoll.find( {x:77} , {name:1, x:1} )
        db.mycoll.find(...).count()
        db.mycoll.find(...).limit(n)
        db.mycoll.find(...).skip(n)
        db.mycoll.find(...).sort(...)
        db.mycoll.findOne([query])
        db.mycoll.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
        db.mycoll.getDB() get DB object associated with collection
        db.mycoll.getIndexes()
        db.mycoll.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
        db.mycoll.insert(obj)
        db.mycoll.mapReduce( mapFunction , reduceFunction , <optional params> )
        db.mycoll.remove(query)
        db.mycoll.renameCollection( newName , <dropTarget> ) renames the collection.
        db.mycoll.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
        db.mycoll.save(obj)
        db.mycoll.stats()
        db.mycoll.storageSize() - includes free space allocated to this collection
        db.mycoll.totalIndexSize() - size in bytes of all the indexes
        db.mycoll.totalSize() - storage allocated for all data and indexes
        db.mycoll.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi


        db.mycoll.validate( <full> ) - SLOW
        db.mycoll.getShardVersion() - only for use with sharding
        db.mycoll.getShardDistribution() - prints statistics about data distribution in the cluster
        db.mycoll.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function

原创粉丝点击