MongoDB 常用命令介绍

在安装MongoDB后,启动服务器进程(mongod),可以通过在客户端命令mongo实现对MongoDB的管理和监控。看一下MongoDB的命令帮助系统。

一、客户端命令:mongo

#./bin/mongo -h

MongoDB shell version: 2.6.8
usage: ./bin/mongo [options] [db address] [file names (ending in .js)]
db address can be:
  foo                   foo database on local machine
  192.169.0.5/foo       foo database on 192.168.0.5 machine
  192.169.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)

Authentication Options:
  -u [ --username ] arg                 username for authentication
  -p [ --password ] arg                 password for authentication
  --authenticationDatabase arg          user source (defaults to dbname)
  --authenticationMechanism arg (=MONGODB-CR)
                                        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
如上可以指定IP、端口、数据库及认证信息(用户名、密码)等连接mongodb数据库。

二、MongoDB最顶层的命令
通过mongo进入数据库,使用help查看MongoDB最顶层的命令列表,主要告诉我们管理数据库相关的一些抽象的范畴:数据库操作帮助、集合操作帮助、管理帮助。

> helphelp
        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.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.createUser(userDocument)
        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.getCollectionInfos()
        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.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.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.listCommands()查询。另一个比较基础的是对指定数据库的集合进行操作、管理和监控,可以通过查询db.mycoll.help()获取到:
> 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.getPlanCache() get query plan cache 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.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
        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
        db.mycoll.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
        db.mycoll.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
        db.mycoll.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
有关数据库和集合管理的相关命令,是最基础和最常用的,如集合查询、索引操作等。
三、常用命令实例
1.超级用户相关

use admin 
#增加或修改用户密码 
db.addUser(ixigua,'pwd') 
#查看用户列表 
db.system.users.find() 
#用户认证 
db.auth(ixigua,'pwd') 
#删除用户 
db.removeUser('mongodb') 
#查看所有用户 
show users 
#查看所有数据库 
show dbs 
#查看所有的collection 
show collections 
#查看各collection的状态 
db.printCollectionStats() 
#查看主从复制状态 
db.printReplicationInfo() 
#修复数据库 
db.repairDatabase() 
#设置记录profiling,0=off 1=slow 2=all 
db.setProfilingLevel(1) 
#查看profiling 
show profile 
#拷贝数据库 
db.copyDatabase('mail_addr','mail_addr_tmp') 
#删除collection 
db.mail_addr.drop() 
#删除当前的数据库 
db.dropDatabase() 

2.数据增删改

#存储嵌套的对象 
db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]}) 
#存储数组对象 
db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']}) 
#根据query条件修改,如果不存在则插入,允许修改多条记录 
db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true) 
#删除yy=5的记录 
db.foo.remove({'yy':5}) 
#删除所有的记录 
db.foo.remove() 
3.索引

#增加索引:1(ascending),-1(descending) 
db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true}); 
#索引子对象 
db.user_addr.ensureIndex({'Al.Em': 1}) 
#查看索引信息 
db.deliver_status.getIndexes() 
db.deliver_status.getIndexKeys() 
#根据索引名删除索引 
db.user_addr.dropIndex('Al.Em_1') 

4.查询

#查找所有 
db.foo.find() 
#查找一条记录 
db.foo.findOne() 
#根据条件检索10条记录 
db.foo.find({'msg':'Hello 1'}).limit(10) 
#sort排序 
db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1}) 
db.deliver_status.find().sort({'Ct':-1}).limit(1) 
#count操作 
db.user_addr.count() 
#distinct操作 
db.foo.distinct('msg') 
#>操作 
db.foo.find({"timestamp": {"$gte" : 2}}) 
#子对象的查找 
db.foo.find({'address.city':'beijing'}) 

5.管理

#查看collection数据的大小 
db.deliver_status.dataSize() 
#查看colleciont状态 
db.deliver_status.stats() 
#查询所有索引的大小 
db.deliver_status.totalIndexSize() 
#查看当前所使用的数据库 
db 
6.条件操作符 

gt:>

lt:< 
gte:
>=

lte:<= 

ne:!=、<>

in:in 
nin:
notin

all: all 
$not: 反匹配(1.3.3及以上版本)

参考文档:

http://blog.csdn.net/shirdrn/article/details/7105539

http://www.jb51.net/article/48217.htm

http://www.cnblogs.com/xusir/archive/2012/12/24/2830957.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值