> 工作中會用到的mongodb數(shù)據(jù)庫相關(guān)命令總結(jié)
連接mongodb
mongo 遠(yuǎn)程主機(jī)ip或DNS:MongoDB端口號/數(shù)據(jù)庫名 -u user -p password mongo 192.168.1.100:27017/test -u user -p password 若在安裝mongo的服務(wù)器上訪問本地mongo,可直接執(zhí)行 mongo
基礎(chǔ)操作命令
show dbs # 顯示數(shù)據(jù)庫列表 show collections # 顯示當(dāng)前數(shù)據(jù)庫中的集合(類似關(guān)系數(shù)據(jù)庫中的表) show users # 顯示用戶 use <db_name> # 切換當(dāng)前數(shù)據(jù)庫,這和MS-SQL里面的意思一樣 db.help() # 顯示數(shù)據(jù)庫操作命令,里面有很多的命令 db.col.help() # 顯示集合操作命令,同樣有很多的命令,col指的是當(dāng)前數(shù)據(jù)庫下,一個叫col的集合(表) db.col.find() #對于當(dāng)前數(shù)據(jù)庫中的col集合進(jìn)行數(shù)據(jù)查找(由于沒有條件,會列出所有數(shù)據(jù)) db.col.find( { a : 1 } ) # 對于當(dāng)前數(shù)據(jù)庫中的col集合進(jìn)行查找,條件是數(shù)據(jù)中有一個屬性叫a,且a的值為1 db.col.find({a:1},{column:0}) # 后面的大括號代表返回字段過濾,column為列名,0代表只去掉該字段,1代表只保留該字段
新增數(shù)據(jù)
db.foo.insert({ "name" : "azhu", "sex": 2, "age": 25})
刪除數(shù)據(jù)
# 刪除指定條件的數(shù)據(jù) db.foo.remove({"userId" : "testcustomer"}) # 清空表 db.foo.remove({}) # 刪除表 db.foo.drop() # 刪除數(shù)據(jù)庫 db.dropDatabase() # 注意,刪除操作是永久性的,不可恢復(fù)的,所以刪除前應(yīng)該使用find確認(rèn)刪除數(shù)據(jù) # 另,mongodb刪除集合后磁盤空間不釋放,用db.repairDatabase()去修復(fù)才能釋放。但是在修復(fù)的過程中如果出現(xiàn)了非正常的mongodb的掛掉,再次啟動時啟動不了的,需要先修復(fù)才可以,可以利用./mongod --repair --dbpath=/data/mongo/,如果你是把數(shù)據(jù)庫單獨(dú)的放在一個文件夾中指定dbpath時就指向要修復(fù)的數(shù)據(jù)庫就可以,修復(fù)可能要花費(fèi)很長的時間,在使用db.repairDatabase()去修復(fù)時一定要停掉讀寫,并且mongodb要有備機(jī)才可以,不然千萬不要隨便使用db.repairDatabase()來修復(fù)數(shù)據(jù)庫,切記。
更新數(shù)據(jù)
db.foo.update({"userId" : "1234"},{'$set':{"usermail" : "[email protected]"}})
查詢數(shù)據(jù)
$gt 大于 > $lt 小于 < $gte 大于等于 >= $lte 小于等于 <= db.col.find({age:{$gt:18}}); # 年齡大于18歲 # SQL -> SELECT * FROM col WHERE age > 18 $ne 不等于 db.col.find({age: {$ne: 18}}).pretty(); # 年齡不等于18歲 # SQL -> select * from col where age != 18 $in $nin db.col.find({name: {$in:[2, 3, 4]}}).pretty() db.col.find({name: {$nin:[2, 3, 4, 5]}}).pretty() $exists db.col.find({title:{$exists:true}}); # 如果記錄中有包含title屬性的全部返回 db.col.find({title:{$exists:false}}); # 如果記錄中有包含title屬性的全部不返回,不包含title屬性的全部返回 db.collection.find({name:/acme.*corp/i}); # 后面的i的意思是區(qū)分大小寫 $ 操作符會限制 array 類型數(shù)據(jù)的返回結(jié)果,使其僅返回第一個滿足條件的元素 db.storage.find( { 'items.category': { $eq: 'food' } }, { 'items.$': 1 } ) $elemMatch 和 $ 的區(qū)別在于,$ 使用的是數(shù)據(jù)查詢條件作為來映射(或者說過濾)array 中的數(shù)據(jù),而 $elemMatch 需要指定單獨(dú)的條件(可以指定多個條件) db.storage.find( // 對 `items` 的過濾條件不需要寫在查詢條件中 { '_id': "alpha" }, { 'items': { '$elemMatch': { 'category': 'food' } } } ) $filter 可以簡單理解為對數(shù)據(jù)的批處理(分組、轉(zhuǎn)換、統(tǒng)計等) db.storage.aggregate( { $project: { "items": { $filter: { input: "$items", as: "item", cond: { $eq: [ '$$item.category', 'food' ] } } } } } )
