1. 程式人生 > >MongoDB命令

MongoDB命令

exists god 獲取 drop 說明 pset 註意 保持 規則


說明:Mongodb命令是區分大小寫的,使用的命名規則是駝峰命名法。
對於database和collection無需主動創建,在插入數據時,如果database和collection不存在則會自動創建。
先用命令行導向D:\\mongoDb\bin\目錄下:
1)help
2)show dbs,show collections/tables
3)use db
例如命令【use demodb】,創建demodb,不用擔心demodb不會創建,當使用use demodb 命令創建第一個collection時會自動創建數據庫demodb,
4)插入db.collectionName.insert({name:"jack",age:33})

5)查詢
查詢所有:db.Student.find();
查詢一條:db.Student.findOne()
查詢指定:db.Student.find({}); 例如:db.Student.find({color:"white"})
說明:find()的第二個參數限制返回的filed的個數,0代表不返回,1代表返回。"_id"鍵總是會被返回。
如果不帶條件,只限制返回的filed個數的話,命令如下:db.Student.find({},{sex:0})。只需要第一個參數為{}空字典就可以。
6)查詢條件

"$lt","$lte","$gt","$gte"分別對應<,<=,>,>=

$ne,不等於,$in,$not和$or

如下代碼: db.Student.find({age:{$gt:33}})

查詢age大於33的
db.Student.find({age:{$gte:33}})
db.Student.find({age:{$lt:33}})
db.Student.find({age:{$lte:33}})
db.Student.find({age:{$gt:23,$lt:43}})
db.Student.find({age:{$ne:33}}) 查詢age不等於33
db.Student.find({color:{$all:["red","blue"]}})

--精確匹配,即被檢索出來的文檔,color值中的數組數據必須和查詢條件完全匹配,即不能多,也不能少,順序也必須保持一致。
db.Student.find({color:["red","blue","black"]})
--匹配數組中指定下標元素的值。數組的起始下標是0。註意color要加引號。
db.Student.find({"color.0":"white"})

7)排序

db.Student.find().sort({age:1})
db.Student.find().sort({age:1,sex:1})

--1代表升序,-1代表降序
8)分頁

db.Student.find().sort({age:1}).limit(3).skip(3)

--limit代表取多少個document,skip代表跳過前多少個document。
9)獲取數量
獲取所有: db.Student.count();
db.Student.count({name:null})
--或者
db.Student.find({name:null}).count()
刪除數據
刪除所有:db.Student.remove({});
刪除指定:db.Student.remove({name:null})
刪除集合:db.Student.drop();

10)更新數據

命令【db.Student.update({name:"jack"},{age:55})】執行後
先查詢name=jack的所有document,然後將name=jack的所有document都替換為{age:55},其它filed都沒有了。
正確的更新方式應該為:
db.Student.update({name:"jack"},{$set:{age:55}})
2.增加field

--將name=lily的student增加一個filed height
db.Student.update({name:"lily"},{$inc:{height:175}})
3.upset-將數字field增加多少增量

--若存在則添加,否則更新,只能用於數字field,例如age更新前是50,更新了185,則變為235.
db.Student.update({name:"lily"},{$inc:{age:185}},true)
4.批量更新數據

4、特殊查詢--null和exists

null可以匹配自身,而且可以匹配"不存在的"

--插入測試數據
db.Student.insert({name:null,sex:1,age:18})
db.Student.insert({sex:1,age:24})

db.Student.find({name:null}) --上面兩條都能查到
db.Student.find({name:{$in:[null],$exists:true}}) ---只能查到第一條
5、數組數據查詢

db.Student.insert({name:"wjh",sex:1,age:18,color:["red","blue","black"]})
db.Student.insert({name:"lpj",sex:1,age:22,color:["white","blue","black"]})
db.Student.find()

MongoDB命令