Mongodb常用命令

4 篇文章 0 订阅
1 篇文章 0 订阅
  1. MongoDb 命令查询所有数据库列表    
  2.     
  3. CODE:    
  4.     
  5. > show dbs    
  6.     
  7. 如果想查看当前连接在哪个数据库下面,可以直接输入db    
  8. CODE:    
  9.     
  10. > db    
  11. Admin    
  12. 想切换到test数据库下面    
  13. CODE:    
  14.     
  15. > use test    
  16. switched to db test    
  17. > db    
  18. Test    
  19. 想查看test下有哪些表或者叫collection,可以输入    
  20. CODE:    
  21.     
  22. > show collections    
  23. system.indexes    
  24. user    
  25. 想知道mongodb支持哪些命令,可以直接输入help    
  26. CODE:    
  27. > help    
  28. Dos代码  收藏代码    
  29.     
  30.     HELP      
  31.           show dbs                     show database names      
  32.           show collections             show collections in current database      
  33.           show users                   show users in current database      
  34.           show profile                 show most recent system.profile entries with time >= 1ms      
  35.           use <db name>                set curent database to <db name>      
  36.           db.help()                    help on DB methods      
  37.           db.foo.help()                help on collection methods      
  38.           db.foo.find()                list objects in collection foo      
  39.           db.foo.find( { a : 1 } )     list objects in foo where a == 1      
  40.           it                           result of the last line evaluated; use to further iterate      
  41.     
  42. 如果想知道当前数据库支持哪些方法:    
  43. CODE:    
  44.     
  45. > db.help();    
  46. Java代码  收藏代码    
  47.     
  48.     DB methods:      
  49.           db.addUser(username, password) 添加数据库授权用户      
  50.           db.auth(username, password)                访问认证      
  51.           db.cloneDatabase(fromhost) 克隆数据库      
  52.           db.commandHelp(name) returns the help for the command      
  53.           db.copyDatabase(fromdb, todb, fromhost)  复制数据库      
  54.           db.createCollection(name, { size : ..., capped : ..., max : ... } ) 创建表      
  55.           db.currentOp() displays the current operation in the db      
  56.           db.dropDatabase()        删除当前数据库      
  57.           db.eval_r(func, args) run code server-side      
  58.           db.getCollection(cname) same as db['cname'] or db.cname      
  59.           db.getCollectionNames()        获取当前数据库的表名      
  60.           db.getLastError() - just returns the err msg string      
  61.           db.getLastErrorObj() - return full status object      
  62.           db.getMongo() get the server connection object      
  63.           db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair      
  64.           db.getName()      
  65.           db.getPrevError()      
  66.           db.getProfilingLevel()      
  67.           db.getReplicationInfo()      
  68.           db.getSisterDB(name) get the db at the same server as this onew      
  69.           db.killOp() kills the current operation in the db      
  70.           db.printCollectionStats()   打印各表的状态信息      
  71.           db.printReplicationInfo()        打印主数据库的复制状态信息      
  72.           db.printSlaveReplicationInfo()        打印从数据库的复制状态信息      
  73.           db.printShardingStatus()                打印分片状态信息      
  74.           db.removeUser(username) 删除数据库用户      
  75.           db.repairDatabase() 修复数据库      
  76.           db.resetError()      
  77.           db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }      
  78.           db.setProfilingLevel(level) 0=off 1=slow 2=all      
  79.           db.shutdownServer()      
  80.           db.version() current version of the server      
  81.     
  82.     
  83. 如果想知道当前数据库下的表或者表collection支持哪些方法,可以使用一下命令如:    
  84. CODE:    
  85.     
  86. > db.user.help();  user为表名    
  87. Java代码  收藏代码    
  88.     
  89.     DBCollection help      
  90.           db.foo.count()                统计表的行数      
  91.           db.foo.dataSize()        统计表数据的大小      
  92.           db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照给定的条件除重      
  93.           db.foo.drop() drop the collection 删除表      
  94.           db.foo.dropIndex(name)  删除指定索引      
  95.           db.foo.dropIndexes() 删除所有索引      
  96.           db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups  增加索引      
  97.           db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return.       
  98.     
  99.     
  100. 根据条件查找数据    
  101. -----------------------    
  102. 通过条件查询: db.foo.find( { x : 77 } , { name : 1 , x : 1 } )    
  103. -----------------------------    
  104.       db.foo.find(...).count()    
  105.       db.foo.find(...).limit(n) 根据条件查找数据并返回指定记录数    
  106.       db.foo.find(...).skip(n)    
  107.       db.foo.find(...).sort(...) 查找排序    
  108.       db.foo.findOne([query]) 根据条件查询只查询一条数据    
  109.       db.foo.getDB() get DB object associated with collection  返回表所属的库    
  110.       db.foo.getIndexes() 显示表的所有索引    
  111.       db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) 根据条件分组    
  112.       db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )    
  113.       db.foo.remove(query) 根据条件删除数据    
  114.       db.foo.renameCollection( newName ) renames the collection  重命名表    
  115.       db.foo.save(obj) 保存数据    
  116.       db.foo.stats()  查看表的状态    
  117.       db.foo.storageSize() - includes free space allocated to this collection 查询分配到表空间大小    
  118.       db.foo.totalIndexSize() - size in bytes of all the indexes 查询所有索引的大小    
  119.       db.foo.totalSize() - storage allocated for all data and indexes 查询表的总大小    
  120.       db.foo.update(query, object[, upsert_bool]) 根据条件更新数据    
  121.       db.foo.validate() - SLOW 验证表的详细信息    
  122.       db.foo.getShardVersion() - only for use with sharding    
  123. Mongodb的备份工具mongodump    
  124.     
  125. 如果想备份数据库test 如:    
  126. CODE:    
  127.     
  128. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongodump --help    
  129. options:    
  130. --help                   produce help message    
  131. -h [ --host ] arg        mongo host to connect to    
  132. -d [ --db ] arg          database to use    
  133. -c [ --collection ] arg  collection to use (some commands)    
  134. -u [ --username ] arg    username    
  135. -p [ --password ] arg    password    
  136. --dbpath arg             directly access mongod data files in this path,    
  137.                          instead of connecting to a mongod instance    
  138. -v [ --verbose ]         be more verbose (include multiple times for more    
  139.                          verbosity e.g. -vvvvv)    
  140. -o [ --out ] arg (=dump) output directory    
  141. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongodump -d test -o test/    
  142. connected to: 127.0.0.1    
  143. DATABASE: test         to         test/test    
  144.       test.user to test/test/user.bson    
  145.                100000 objects    
  146.       test.system.indexes to test/test/system.indexes.bson    
  147.                1 objects    
  148. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ls    
  149. 2     mongo   mongodump    mongofiles   mongorestore  mongosniff    
  150. dump  mongod  mongoexport  mongoimport  mongos     test    
  151. MongoDB的数据恢复工具mongorestore    
  152.     
  153. 查看test库中的表    
  154. CODE:    
  155.     
  156. > show collections    
  157. system.indexes    
  158. User    
  159. 删除user表    
  160. CODE:    
  161.     
  162. > db.user.drop();    
  163. True    
  164.     
  165. > show collections    
  166. System.indexes    
  167. 现在利用mongorestore表恢复刚才利用mongodump备份的数据    
  168. CODE:    
  169.     
  170. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore --help    
  171. usage: ./mongorestore [options] [directory or filename to restore from]    
  172. options:    
  173. --help                  produce help message    
  174. -h [ --host ] arg       mongo host to connect to    
  175. -d [ --db ] arg         database to use    
  176. -c [ --collection ] arg collection to use (some commands)    
  177. -u [ --username ] arg   username    
  178. -p [ --password ] arg   password    
  179. --dbpath arg            directly access mongod data files in this path,    
  180.                         instead of connecting to a mongod instance    
  181. -v [ --verbose ]        be more verbose (include multiple times for more    
  182.                         verbosity e.g. -vvvvv)    
  183.     
  184. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore -d test -c user test/test/user.bson    
  185. connected to: 127.0.0.1    
  186. test/test/user.bson    
  187.        going into namespace [test.user]    
  188.     
  189.        100000 objects    
  190. User表中的10w条记录已经恢复    
  191. CODE:    
  192.     
  193. > show collections    
  194. system.indexes    
  195. user    
  196. > db.user.find();    
  197. "_id" : ObjectId("4b9c8db08ead0e3347000000"), "uid" : 1"username" : "Falcon.C-1" }    
  198. "_id" : ObjectId("4b9c8db08ead0e3347010000"), "uid" : 2"username" : "Falcon.C-2" }    
  199. "_id" : ObjectId("4b9c8db08ead0e3347020000"), "uid" : 3"username" : "Falcon.C-3" }    
  200. "_id" : ObjectId("4b9c8db08ead0e3347030000"), "uid" : 4"username" : "Falcon.C-4" }    
  201. "_id" : ObjectId("4b9c8db08ead0e3347040000"), "uid" : 5"username" : "Falcon.C-5" }    
  202. .................    
  203. has more    
  204.     
  205.     
  206.     
  207.     
  208.     
  209.    1. 超级用户相关:    
  210.     
  211.          #增加或修改用户密码    
  212.     
  213.          db.addUser('admin','pwd')    
  214.     
  215.          #查看用户列表    
  216.     
  217.          db.system.users.find()    
  218.     
  219.          #用户认证    
  220.     
  221.          db.auth('admin','pwd')    
  222.     
  223.          #删除用户    
  224.     
  225.          db.removeUser('mongodb')    
  226.     
  227.          #查看所有用户    
  228.     
  229.          show users    
  230.     
  231.          #查看所有数据库    
  232.     
  233.          show dbs    
  234.     
  235.          #查看所有的collection    
  236.     
  237.          show collections    
  238.     
  239.          #查看各collection的状态    
  240.     
  241.          db.printCollectionStats()    
  242.     
  243.          #查看主从复制状态    
  244.     
  245.          db.printReplicationInfo()    
  246.     
  247.          #修复数据库    
  248.     
  249.          db.repairDatabase()    
  250.     
  251.          #设置记录profiling,0=off 1=slow 2=all    
  252.     
  253.          db.setProfilingLevel(1)    
  254.     
  255.          #查看profiling    
  256.     
  257.          show profile    
  258.     
  259.          #拷贝数据库    
  260.     
  261.          db.copyDatabase('mail_addr','mail_addr_tmp')    
  262.     
  263.          #删除collection    
  264.     
  265.          db.mail_addr.drop()    
  266.     
  267.          #删除当前的数据库    
  268.     
  269.          db.dropDatabase()    
  270.     
  271.    2. 客户端连接    
  272.     
  273.           /usr/local/mongodb/bin/mongo user_addr -u user -p 'pwd'    
  274.     
  275.    3. 增删改    
  276.     
  277.            #存储嵌套的对象    
  278.     
  279.           db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})    
  280.     
  281.           #存储数组对象    
  282.     
  283.           db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})    
  284.     
  285.           #根据query条件修改,如果不存在则插入,允许修改多条记录    
  286.     
  287.           db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)    
  288.     
  289.           #删除yy=5的记录    
  290.     
  291.           db.foo.remove({'yy':5})    
  292.     
  293.           #删除所有的记录    
  294.     
  295.          db.foo.remove()    
  296.     
  297.    4. 索引    
  298.     
  299.           增加索引:1(ascending),-1(descending)    
  300.     
  301.           db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});    
  302.     
  303.           #索引子对象    
  304.     
  305.           db.user_addr.ensureIndex({'Al.Em'1})    
  306.     
  307.           #查看索引信息    
  308.     
  309.           db.deliver_status.getIndexes()    
  310.     
  311.           db.deliver_status.getIndexKeys()    
  312.     
  313.           #根据索引名删除索引    
  314.     
  315.           db.user_addr.dropIndex('Al.Em_1')    
  316.     
  317.    5. 查询    
  318.     
  319.           查找所有    
  320.     
  321.           db.foo.find()    
  322.     
  323.           #查找一条记录    
  324.     
  325.           db.foo.findOne()    
  326.     
  327.           #根据条件检索10条记录    
  328.     
  329.           db.foo.find({'msg':'Hello 1'}).limit(10)    
  330.     
  331.           #sort排序    
  332.     
  333.           db.deliver_status.find({'From':'yushunzhi@sohu.com'}).sort({'Dt',-1})    
  334.     
  335.           db.deliver_status.find().sort({'Ct':-1}).limit(1)    
  336.     
  337.          #count操作    
  338.     
  339.          db.user_addr.count()    
  340.     
  341.          #distinct操作    
  342.     
  343.          db.foo.distinct('msg')    
  344.     
  345.          #>操作    
  346.     
  347.          db.foo.find({"timestamp": {"$gte" : 2}})    
  348.     
  349.          #子对象的查找    
  350.     
  351.          db.foo.find({'address.city':'beijing'})    
  352.     
  353.    6. 管理    
  354.     
  355.           查看collection数据的大小    
  356.     
  357.           db.deliver_status.dataSize()    
  358.     
  359.           #查看colleciont状态    
  360.     
  361.           db.deliver_status.stats()    
  362.     
  363.           #查询所有索引的大小    
  364.     
  365.           db.deliver_status.totalIndexSize()    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值