db.post.findOne({ id :1}) { &nbs..."/>
您好,登錄后才能下訂單哦!
查看一個文檔的一個鍵值comments為一個數(shù)組[“test1”,”test2”]:
> db.post.findOne({"id":1}) { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test1", "test2" ] } >
一、$push向數(shù)組末尾添加元素
> 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刪除數(shù)組中的元素
從數(shù)組末尾刪除一個值:
> 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" ] }
從數(shù)組開頭刪除一個值:
> 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" ] } >
三、刪除數(shù)組中一個指定的值:
> 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" ] } >
四、基于數(shù)組下標(biāo)位置修改:
> 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" ] } >
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。