您好,登錄后才能下訂單哦!
一、批量更新
默認只對符合條件的一條文檔更新
> db.post.find() { "_id" : ObjectId("54a530c3ff0df3732bac1681"), "id" : 2, "name" : "joe", "age" : 49 } { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test2", "test9", "test5" ] } > db.post.update({"name":"joe"}, {$set:{"age":70}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.post.find() { "_id" : ObjectId("54a530c3ff0df3732bac1681"), "id" : 2, "name" : "joe", "age" : 70 } { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 21, "comments" : [ "test2", "test9", "test5" ] } >
利用update的第四個參數進行批量更新:
> db.post.update({"name":"joe"}, {$set:{"age":30}},false,true) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })> db.post.find() { "_id" : ObjectId("54a530c3ff0df3732bac1681"), "id" : 2, "name" : "joe", "age" : 30 } { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 30, "comments" : [ "test2", "test9", "test5" ] } >
附注:update方法參考
update( criteria, objNew, upsert, multi )
criteria : update的查詢條件,類似sql update查詢內where后面的
objNew : update的對象和一些更新的操作符(如$,$inc...)等,也可以理解為sql update查詢內set后面的
upsert : 這個參數的意思是,無論false還是true,沒有匹配的鍵則新增加一個;
multi : mongodb默認是false,只更新找到的第一條記錄,如果這個參數為true,就把按條件查出來多條記錄全部更新。
二、更新文檔鍵值,無鍵值的則新增鍵值;
> db.post.update({"name":"joe"}, {$set:{"sex":1}},false,true) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) > db.post.find() { "_id" : ObjectId("54a530c3ff0df3732bac1681"), "id" : 2, "name" : "joe", "age" : 30, "sex" : 1 } { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 30, "comments" : [ "test2", "test9", "test5" ], "sex" : 1 } > db.post.update({"name":"joe"}, {$set:{"school":"marry"}},true,true) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) > db.post.find() { "_id" : ObjectId("54a530c3ff0df3732bac1681"), "id" : 2, "name" : "joe", "age" : 30, "sex" : 1, "school" : "marry" } { "_id" : ObjectId("54a530c3ff0df3732bac1680"), "id" : 1, "name" : "joe", "age" : 30, "comments" : [ "test2", "test9", "test5" ], "sex" : 1, "school" : "marry" } >
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。