一、批量更新
創(chuàng)新互聯(lián)建站咨詢(xún)熱線:18980820575,為您提供成都網(wǎng)站建設(shè)網(wǎng)頁(yè)設(shè)計(jì)及定制高端網(wǎng)站建設(shè)服務(wù),創(chuàng)新互聯(lián)建站網(wǎng)頁(yè)制作領(lǐng)域10年,包括成都酒樓設(shè)計(jì)等多個(gè)方面擁有多年的網(wǎng)站設(shè)計(jì)經(jīng)驗(yàn),選擇創(chuàng)新互聯(lián)建站,為企業(yè)保駕護(hù)航!
默認(rèn)只對(duì)符合條件的一條文檔更新
> 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的第四個(gè)參數(shù)進(jìn)行批量更新:
> 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的查詢(xún)條件,類(lèi)似sql update查詢(xún)內(nèi)where后面的
objNew : update的對(duì)象和一些更新的操作符(如$,$inc...)等,也可以理解為sql update查詢(xún)內(nèi)set后面的
upsert : 這個(gè)參數(shù)的意思是,無(wú)論false還是true,沒(méi)有匹配的鍵則新增加一個(gè);
multi : MongoDB默認(rèn)是false,只更新找到的第一條記錄,如果這個(gè)參數(shù)為true,就把按條件查出來(lái)多條記錄全部更新。
二、更新文檔鍵值,無(wú)鍵值的則新增鍵值;
> 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" } >