一、批量更新
默认只对符合条件的一条文档更新
> 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。