首页 > 数据库 > MongoDB > 正文

浅谈MongoDB中的常用操作,你都知道多少?

2022-07-04 18:37:40
字体:
来源:转载
供稿:网友
       这篇文章给大家分享的是有关MongoDB中的常用操作的内容,小编觉得挺实用的,因此分享给大家做个参考。下文整理了很多MongoDB操作技巧,感兴趣的朋友接下来一起跟随小编看看吧。
 
       1、shell登陆和显示
 
       假设在本机上有一个端口为17380的MongoDB服务,假设已经把mongo bin文件加入到系统PATH下。
 
       登陆:mongo --port 17380
 
      显示DB:show dbs
 
       进入某DB:use test_cswuyg
 
       显示集合:show tables
 
    2、简单查找
    查找文档:db.test_mac_id.find({'a': 'b'})
 
    删除文档:db.test_mac_id.remove({'a': 'b'})
 
    查找找到某一天的数据:
 
    db.a.find({'D' : ISODate('2014-04-21T00:00:00Z')}) 或者 db.a.find({'D' : ISODate('2014-04-21')})
 
    删除某一天的数据:
 
    db.region_mac_id_result.remove({"D" : ISODate('2014-04-17')})
 
    小于2014.6.5的数据:
 
    db.xxx.find({E: {$lt :ISODate('2014-06-05')}})
 
    大于等于2014.6.1的数据:
 
    db.xxx.find({E: {$gte: ISODate("2014-05-29")}}).count()
 
    两个条件:
 
    db.xxx.find({E:{$gte: ISODate("2014-05-29"), $lte: ISODate("2014-06-04")}}).count()
 
    json中的嵌套对象查询,采用“点”的方式:
 
    mongos> db.wyg.find({"a.b": {$exists: true}})
 
    { "_id" : "c", "a" : { "b" : 10 } }
 
    某个字段存在,且小于1000有多少:
 
    db.stat.find({_: ISODate("2014-06-17"), "123": {$exists: 1, $lte: 1000}}, {"123": 1}).count()
 
    3、存在和遍历统计
    存在'i': 1,且存在old_id字段:
 
    mongos> var it = db.test.find({'i': 1, "old_id": {$exists: 1}})
 
    遍历计数1:mongos> var count = 0;while(it.hasNext()){if (it.next()["X"].length==32)++count}print(count)
 
    遍历计数2:mongos> var count = 0;while(it.hasNext()){var item = it.next(); if (item['X'].length==32 && item['_id'] != item['X'])++count;if(!item['X'])++count;}print(count)
 
    4、插入和更新
    > db.test.findOne({_id: 'cswuyg'})
 
    null
 
    > db.test.insert({'_id': 'cswuyg', 'super_admin': true})
 
    > db.test.findOne({'_id': 'cswuyg'})
 
    {
 
    "_id" : "cswuyg",
 
    "super_admin" : true
 
    }
 
    db.test.update({'_id': 'cswuyg'}, {$set: {'super_admin': true}})
 
    5、repair 操作
    对某个DB执行repair:进入要repair的db,执行db.repairDatabase()
 
    对mongodb整个实例执行repair:numactl --interleave=all /mongod --repair --dbpath=/home/disk1/mongodata/shard/
 
    6、mongodb任务操作
    停止某个操作:
 
[xxx]$ mongo --port 17380
MongoDB shell version: 2.4.5
connecting to: 127.0.0.1:17380/test
mongos> db.currentOp()
{ "inprog" : [ ...] }
 
mongos> db.killOp("shard0001:163415563")
    批量停止:
 
    db.currentOp().inprog.forEach(function(item){db.killOp(item.opid)})
    当查询超过1000秒的,停止:
 
    db.currentOp().inprog.forEach(function(item){if(item.secs_running > 1000 )db.killOp(item.opid)})
    停止某个数据源的查询:
 
    db.currentOp().inprog.forEach(function(item){if(item.ns == "cswuyg.cswuyg")db.killOp(item.opid)})
    把所有在等待锁的操作显示出来:
 
    db.currentOp().inprog.forEach(function(item){if(item.waitingForLock)print(JSON.stringify(item))})
    把处于等待中的分片显示出来:
 
     常用js脚本,可直接复制到mongo-shell下使用:
 
    显示当前所有的任务状态:
 
print("##########");db.currentOp().inprog.forEach(function(item){if(item.waitingForLock){var lock_info = item["opid"];
print("waiting:",lock_info,item.op,item.ns);}});print("----");
db.currentOp().inprog.forEach(function(item){if(!item.waitingForLock){var lock_info = item["opid"];
print("doing",lock_info,item.op,item.ns);}});print("##########");
    杀掉某些特定任务:
 
    (1)
 
    db.currentOp().inprog.forEach(function(item){if(item.waitingForLock){var lock_info = item["opid"];if(item.op=="query" && item.secs_running >60 && item.ns=="cswuyg.cswuyg"){db.killOp(item.opid)}}})
    (2)
 
db.currentOp().inprog.forEach(function(item) {
 var lock_info = item["opid"];
 if (item.op == "query" && item.secs_running > 1000) {
 print("kill", item.opid);
 db.killOp(item.opid)
 }
})
    7、删除并返回数据
    old_item = db.swuyg.findAndModify({query: {"_id": "aabbccdd"}, fields:{"D": 1,'E':1, 'F':1}, remove: true})
 
    fields里面为1的是要返回的数据。
 
    8、分布式集群部署情况
    (1) 细致到collection的显示:sh.status()
 
    (2)仅显示分片:
 
    use config; db.shards.find()
 
    { "_id" : "shard0000", "host" : "xxhost:10001" }
 
    { "_id" : "shard0001", "host" : "yyhost:10002" }
 
    ....
 
    (3)
 
    use admin
 
    db.runCommand({listshards: 1})
 
    列出所有的shard server
 
    9、正则表达式查找
    正则表达式查询:
    mongos> db.a.find({"tt": /t*/i})
    { "_id" : ObjectId("54b21e0f570cb10de814f86b"), "aa" : "1", "tt" : "tt" }
    其中i表明是否是case-insensitive,有i则表示忽略大小写
 
    db.testing.find({"name":/[7-9]/})
 
    当name的值为789这几个数字组成的字符串时,查询命中。
 
    10、查询性能
    db.testing.find({name: 123}).explain()
 
    输出结果:
 
{
  "cursor" : "BasicCursor",
  "isMultiKey" : false,
  "n" : 1,
  "nscannedObjects" : 10,
  "nscanned" : 10,
  "nscannedObjectsAllPlans" : 10,
  "nscannedAllPlans" : 10,
  "scanAndOrder" : false,
  "indexOnly" : false,
  "nYields" : 0,
  "nChunkSkips" : 0,
  "millis" : 0,
  "indexBounds" : {
  },
  "server" : "xxx:10001"
}
    11、更新或插入
    当该key不存在的时候执行插入操作,当存在的时候则不管,可以使用setOnInsert
 
    db.wyg.update({'_id': 'id'}, {'$setOnInsert': {'a': 'a'}, '$set': {'b': 'b'}}, true)
 
    当id存在的时候,忽略setOnInsert。
 
    当id存在的时候,如果要插入,则插入{'a': 'a'}
 
    最后的参数true,则是指明,当update不存在的_id时,执行插入操作。默认是false,只更新,不插入。
 
    push、setOnInsert:db.cswuyg.update({"_id": "abc"}, {$push: {"name": "c"}, $setOnInsert: {"cc":"xx"}}, true)
 
    12、计算DB中collection的数量
    db.system.namespaces.count()
 
    13、增加数字,采用$inc
    db.cswuyg.update({"a.b": {$exists: true}}, {$inc: {'a.b': 2}})
 
    也就是对象a.b的值,增加了2
 
    注意$inc只能用于数值。
 
    14、删除某个key
    db.cswuyg.update({'_id': 'c'}, {$unset: {'b': {$exists: true}}})
 
    { "_id" : "c", "a" : { "b" : 12 }, "b" : 7 }
 
    转变为:
 
    { "_id" : "c", "a" : { "b" : 12 } }
 
    15、增加key:value
    db.cswuyg.update({'_id': 'z'}, {'$set': {'hello': 'z'}})
 
    { "_id" : "z", "b" : 1 }
 
    转变为:
 
    { "_id" : "z", "b" : 1, "hello" : "z" }
 
    16、删除数据库、删除表
    删除数据库:db.dropDatabase();
 
    删除表:db.mytable.drop();
 
    17、查找到数据只看某列
    只显示key名为D的数据:db.test.find({}, {D: 1})
 
    18、查看分片存储情况
    (1)所有DB的分片存储信息,包括chunks数、shard key信息:db.printShardingStatus()
 
    (2)db.collection.getShardDistribution() 获取collection各个分片的数据存储情况
 
    (3)sh.status() 显示本mongos集群所有DB的信息, 包含了Shard Key信息
 
    19、查看collection的索引
    db.cswuyg.getIndexes()
 
    20、开启某collection的分片功能
    1. ./bin/mongo -Cport 20000
 
    2. mongos> use admin
 
    3. switched to db admin
 
    4. mongos> db.runCommand({'enablesharding"' 'test'})
 
    5. { "ok" : 1 }
 
    开启user collection分片功能:
 
    1. mongos> db.runCommand({'shardcollection': 'test.user', 'key': {'_id': 1}})
 
    { "collectionsharded" : "test.user", "ok" : 1 }
 
    21、判断当前是否是shard集群
    isdbgrid:用来确认当前是否是 Sharding Cluster
 
> db.runCommand({isdbgrid:1});
是:
{ "isdbgrid" : 1, "hostname" : "xxxhost", "ok" : 1 }
不是:
{
  "ok" : 0,
  "errmsg" : "no such cmd: isdbgrid",
  "code" : 59,
  "bad cmd" : {
    "isdbgrid" : 1
  }
}
    22、dump DB
    mongodump支持从DB磁盘文件、运行中的MongoD服务中dump出bson数据文件。
 
    (1)关闭MongoD之后,从它的DB磁盘文件中dump出数据(注:仅限单实例mongod):
 
    mongodump --dbpath=/home/disk1/mongodata/shard/ -d cswuyg -o /home/disk2/mongodata/shard
 
    参考:
 
    http://docs.mongodb.org/manual/reference/program/mongodump/
 
    http://stackoverflow.com/questions/5191186/how-do-i-dump-data-for-a-given-date
 
    (2)从运行的MongoD中导出指定日期数据,采用-q查询参数:
 
    mongodump -h xxxhost --port 17380 --db cswuyg --collection test -q "{D: {/$gte: {/$date: `date -d "20140410" +%s`000}, /$lt: {/$date: `date +%s`000}}}"
 
    mongodump -dbpath=/home/disk3/mongodb/data/shard1/ -d cswuyg -c test -o /home/disk9/mongodata/shard1_2/ -q "{_:{/$gte:{/$date:`date -d "20140916" +%s`000}, /$lt: {/$date: `date -d "20140918" +%s`000}}}"
 
    dump出来的bson文件去掉了索引、碎片空间,所有相比DB磁盘文件要小很多。

(编辑:错新网)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表