您好,登錄后才能下訂單哦!
查看一個文檔的一個鍵值comments為一個數組[“test1”,”test2”]:
> db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test1", "test2" ] } >
一、$push向數組末尾添加元素
> db.post.update({"id":1},{$push:{"comments": "test3"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test1", "test2", "test3" ] } >
使用$each一次性添加多個值:
> db.post.update({"id":1},{$push:{"comments":{$each:["test4","test5","test6"]}}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test1", "test2", "test3", "test4", "test5", "test6" ] } >
二、用$pop刪除數組中的元素
從數組末尾刪除一個值:
> db.post.update({"id":1},{$pop:{"comments":1}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test1", "test2", "test3", "test4", "test5" ] }
從數組開頭刪除一個值:
> db.post.update({"id":1},{$pop:{"comments":-1}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test2", "test3", "test4", "test5" ] } >
三、刪除數組中一個指定的值:
> db.post.update({"id":1},{$pull:{"comments":"test3"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test2", "test4", "test5" ] } >
四、基于數組下標位置修改:
> db.post.update({"id":1},{$set:{"comments.1":"test9"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test2", "test9", "test5" ] } >
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。