1. 程式人生 > >Mongodb 常用命令整理

Mongodb 常用命令整理

一、超級使用者相關:

  • 進入資料庫admin 
    use admin

  • 增加或修改使用者密碼 
    db.addUser(‘name’,’pwd’)

  • 檢視使用者列表 
    db.system.users.find()

  • 使用者認證 
    db.auth(‘name’,’pwd’)

  • 刪除使用者 
    db.removeUser(‘name’)

  • 檢視所有使用者 
    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()

二、增刪改

  • 儲存巢狀的物件 
    db.foo.save({‘name’:’imdst’,’address’:{‘city’:’guangzhou’,’post’:100096},’phone’:[158,155]})

  • 儲存陣列物件 
    db.user_addr.save({‘Uid’:’[email protected]’,’Al’:['[email protected]','[email protected]']})

  • 根據query條件修改,如果不存在則插入,允許修改多條記錄 
    db.foo.update({‘yy’:5},{‘$set’:{‘xx’:2}},upsert=true,multi=true)

  • 刪除yy=5的記錄 
    db.foo.remove({‘yy’:5})

  • 刪除所有的記錄 
    db.foo.remove()

三、索引

  • 增加索引 1(ascending),-1(descending) 
    db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});

  • 索引子物件 
    db.user_addr.ensureIndex({‘Al.Em’: 1})

  • 檢視索引資訊 
    db.foo.getIndexes() 
    db.foo.getIndexKeys()

  • 根據索引名刪除索引 
    db.user_addr.dropIndex(‘Al.Em_1′)

四、查詢

  • 查詢所有 
    db.foo.find()

  • 查詢一條記錄 
    db.foo.findOne()

  • 根據條件檢索10條記錄 
    db.foo.find({‘msg’:’Hello 1′}).limit(10)

  • sort排序 
    db.deliver_status.find({‘From’:’[email protected]’}).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’})

五、管理

  • 檢視collection資料的大小 
    db.deliver_status.dataSize()

  • 檢視colleciont狀態 
    db.deliver_status.stats()

  • 查詢所有索引的大小 
    db.deliver_status.totalIndexSize()
  • advanced queries:高階查詢
條件操作符
$gt : >
$lt : <<br> $gte: >=
$lte: <=
$ne : !=、<>
$in : in
$nin: not in
$all: all
$not: 反匹配(1.3.3及以上版本)
  • 查詢 name <> “bruce” and age >= 18 的資料 
    db.users.find({name: {$ne: “bruce”}, age: {$gte: 18}});

  • 查詢 creationdate > ’2010-01-01′ and creationdate <= ’2010-12-31′ 的資料 
    db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});

  • 查詢 age in (20,22,24,26) 的資料 
    db.users.find({age: {$in: [20,22,24,26]}});

  • 查詢 age取模10等於0 的資料 
    db.users.find(‘this.age % 10 == 0′); 
    db.users.find({age : {$mod : [10, 0]}});

  • 查詢所有name欄位是字元型別的 
    db.users.find({name: {$type: 2}});

  • 查詢所有age欄位是整型的 
    db.users.find({age: {$type: 16}});

  • 對於字元欄位,可以使用正則表示式 查詢以字母b或者B帶頭的所有記錄 
    db.users.find({name: /^b.*/i});

  • 匹配所有 
    db.users.find({favorite_number : {$all : [6, 8]}});

  • 查詢不匹配name=B*帶頭的記錄 
    db.users.find({name: {$not: /^B.*/}});

  • 查詢 age取模10不等於0 的資料 
    db.users.find({age : {$not: {$mod : [10, 0]}}});

  • 選擇返回age和id欄位(id欄位總是會被返回) 
    db.users.find({}, {age:1}); 
    db.users.find({}, {age:3}); 
    db.users.find({}, {age:true}); 
    db.users.find({ name : “bruce” }, {age:1}); 
    0為false, 非0為true

  • 選擇返回age、address和_id欄位 
    db.users.find({ name : “bruce” }, {age:1, address:1});

  • 排除返回age、address和_id欄位 
    db.users.find({}, {age:0, address:false}); 
    db.users.find({ name : “bruce” }, {age:0, address:false});

  • 查詢所有存在name欄位的記錄 
    db.users.find({name: {$exists: true}});

  • 排序sort()

    • 查詢所有不存在phone欄位的記錄 
      db.users.find({phone: {$exists: false}});

    • 排序sort() 以年齡升序asc 
      db.users.find().sort({age: 1});

    • 以年齡降序desc 
      db.users.find().sort({age: -1});

  • 限制返回記錄數量limit()

    • 返回5條記錄 
      db.users.find().limit(5);
    • 返回3條記錄並列印資訊 
      db.users.find().limit(3).forEach(function(user) {print(‘my age is ‘ + user.age)}); 
      結果 
      my age is 18 
      my age is 19 
      my age is 20
  • 限制返回記錄的開始點skip()

    • 從第3條記錄開始,返回5條記錄(limit 3, 5) 
      db.users.find().skip(3).limit(5);
    • 查詢記錄條數count() 
      db.users.find().count(); 
      db.users.find({age:18}).count();
    • 以下返回的不是5,而是user表中所有的記錄數量 
      db.users.find().skip(10).limit(5).count();
    • 如果要返回限制之後的記錄數量,要使用count(true)或者count(非0) 
      db.users.find().skip(10).limit(5).count(true);
  • 分組group()

    • 假設test表只有以下一條資料
{ domain: “www.mongodb.org”
, invoked_at: {d:”2015-05-03″, t:”17:14:05″}
, response_time: 0.05
, http_action: “GET /display/DOCS/Aggregation”
}
  • 使用group統計test表11月份的資料count:count(*)、totaltime:sum(responsetime)、avgtime:totaltime/count;
db.test.group(  
{ cond: {“invoked_at.d”: {$gt: “2015-05″, $lt: “2015-06″}}
, key: {http_action: true}
, initial: {count: 0, total_time:0}
, reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
, finalize: function(out){ out.avg_time = out.total_time / out.count }
} );
[
{
"http_action" : "GET /display/DOCS/Aggregation",
"count" : 1,
"total_time" : 0.05,
"avg_time" : 0.05
}
]