首頁  >  文章  >  資料庫  >  MongoDB中常用的語句總結

MongoDB中常用的語句總結

不言
不言轉載
2018-10-17 14:49:392116瀏覽

這篇文章帶給大家的內容是關於MongoDB中常用的語句總結,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

如果覺得 Mongodb 語句不太好理解,可以和 SQL 語句做對比,學起來要容易很多。

1. 查詢(find)

查詢所有結果

select * from article
db.article.find()

指定回傳哪些鍵

select title, author from article
db.article.find({}, {"title": 1, "author": 1})

where條件

select * from article where title = "mongodb"
db.article.find({"title": "mongodb"})

and條件

select * from article where title = "mongodb" and author = "god"
db.article.find({"title": "mongodb", "author": "god"})

or條件

select * from article where title = "mongodb" or author = "god"
db.article.find({"$or": [{"title": "mongodb"}, {"author": "god"}]})

比較條件

select * from article where read >= 100;
db.article.find({"read": {"$gt": 100}})
> $gt(>)、$gte(>=)、$lt(d465e952edbc4325ec7a8892c05fa947= 100 and read fc8d0d787275f5d74383b1c74eca291e 100
db.article.update({"read": {"$gt": 100}}, {"$set": { "title": "mongodb"}})

save()

db.article.save({_id: 123, title: "mongodb"})

執行上面的語句,如果集合中已經存在一個_id為123的文檔,則更新對應字段;否則插入。

附註:如果更新物件不存在_id,系統會自動產生並插入為新的文件。

更新操作符

MongoDB提供一些強大的更新操作符。

更新特定欄位($set):

update game set count = 10000 where _id = 123
db.game.update({"_id": 123}, { "$set": {"count": 10000}})

刪除特定欄位($unset):

註:$unset指定欄位的值只需是任意合法值即可。
遞增或遞減($inc)

 db.game.update({"_id": 123}, { "$inc": {"count": 10}}) // 每次count都加10

> 注意:$inc對應的欄位必須是數字,而且遞增或遞減的值也必須是數字。

陣列追加($push):

 db.game.update({"_id": 123}, { "$push": {"score": 123}})

也可以一次追加多個元素:

 db.game.update({"_id": 123}, {"$push": {"score": [12,123]}})

註:追加欄位必須是陣列。如果陣列欄位不存在,則自動新增,然後追加。

一次追加多個元素($pushAll):

 db.game.update({"_id": 123}, {"$pushAll": {"score": [12,123]}})

追加不重複元素($addToSet):

$addToSet類似集合Set,只有當這個值不在元素內時才增加:

 db.game.update({"_id": 123}, {"$addToSet": {"score": 123}})

刪除元素($pop):

db.game.update({"_id": 123}, {"$pop": {"score": 1}})  // 删除最后一个元素
db.game.update({"_id": 123}, {"$pop": {"score": -1}})  // 删除第一个元素

註:$pop每次只能刪除陣列中的一個元素,1表示刪除最後一個,-1表示刪除第一個。

刪除特定元素($pull):

db.game.update({"_id": 123}, {"$pull": {"score": 123}})

上面的語句表示刪除陣列score內值等於123的元素。

刪除多個特定元素($pullAll):

db.game.update({"_id": 123}, {"$pullAll": {score: [123,12]}})

上面的語句表示刪除陣列內值等於123或12的元素。
更新巢狀數組的值:
使用數組下標(從0開始):

{
    address: [{place: "nanji", tel: 123}, {place: "dongbei", tel: 321}]
}
 db.game.update({"_id": 123}, {"$set": {"address.0.tel": 213}})

如果你不知道要更新數組哪項,我們可以使用$運算元( $表示自身,也就是依查詢條件找出的陣列裡面的項自身,而且只會套用找到的第一個陣列項目):

 db.game.update({"address.place": "nanji"}, {"$set": {"address.$.tel": 123}})

在上面的語句中,$就是查詢條件{"address.place": "nanji"}的查詢結果,也就是{place: "nanji", tel: 123},所以{"address.$.tel": 123}也就是{"address.{place : "nanji", tel: 123}.tel": 123}

4. 刪除(remove)

##刪除所有文件:

delete from article
db.article.remove()

刪除指定文件:

 delete from article where title = "mongodb"
 db.article.remove({title: "mongodb"})

以上是MongoDB中常用的語句總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除