MongoDB基本操作(包括插入、修改、子節點排序等)


一、基本操作

1.新增文章

db.article.insert({title:"今天天氣很好",content:"我們一起去春游",_id:1})

 2.新增一條評論

db.article.update({_id:1},{"$set":{comments:[{user:"duanjt",time:new Date("2019-01-30")}]}})

 說明:$set表示替換comments節點的內容

3.再增加四條評論

db.article.update({_id:1},{"$addToSet":{comments:{"$each":[{user:"zhuzhu",time:new Date("2019-01-31")}]}}});
db.article.update({_id:1},{"$addToSet":{comments:{"$each":
[
    {user:"lisi",time:new Date("2019-01-20")},
    {user:"wangwu",time:new Date("2019-01-11")},
    {user:"taoge",time:new Date("2019-01-12")}
]
}}});
db.article.update({_id:1},{"$push":{comments:{"$each":[{user:"chaoling",time:new Date("2019-01-31")}]}}});

 說明:$addToSet表示在節點comments中增加內容。而$each表示將后面指定的數組一個一個插入到comments節點里面。

在這里addToSet和push感覺作用是一樣的。

4.查詢前2條評論

db.article.find({_id:1},{"comments":{"$slice":[0,2]}});

5.將評論里面用戶是“wangwu”的修改為“王五”

db.article.update(
    {"_id":1,"comments.user":"wangwu"},
    {"$set":{"comments.$.user":"王五"}}
)

 

注意:comments.$.user中的$是一個占位,表示當前匹配的數據行

6.將comments里面的內容按時間或名稱排序

db.article.update({_id:1},{"$push":{comments:{"$each":[],"$sort":{"time":1}}}});
db.article.update({_id:1},{"$push":{comments:{"$each":[],"$sort":{"user":1}}}});

 說明:由於MongoDB不提供針對子節點的直接排序方法,所以我們只能通過變通的方式,插入一個空數組,然后再排序。排序完了之后再通過第四步的方法獲取數據。


二、關於push和addToSet的區別

db.user.insert({_id:1,name:"段江濤",likes:["學習","勞動"]});    //插入數據,愛好是學習和勞動
db.user.update({_id:1},{"$push":{"likes":{"$each":["學習"]}}});    //通過push增加一個“學習”的愛好,能新增成功
db.user.update({_id:1},{"$addToSet":{"likes":{"$each":["學習"]}}});    //通過addToSet增加一個“學習”的愛好,操作不報錯,但是不會新增成功。

 結論:push直接插入,而addToSet會自動排除重復的數據。此外push支持$sort $position $slice,可以控制插入元素的位置、排序和限制元素數量

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM