且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MongoDB:如何使用单个命令更新多个文档?

更新时间:2023-02-14 08:39:43

最近添加了多个更新,因此仅在开发版本 (1.1.3) 中可用.在 shell 中,您通过将 true 作为第四个参数传递给 update() 来执行多重更新,其中第三个参数是 upsert 参数:

Multi update was added recently, so is only available in the development releases (1.1.3). From the shell you do a multi update by passing true as the fourth argument to update(), where the the third argument is the upsert argument:

db.test.update({foo: "bar"}, {$set: {test: "success!"}}, false, true);

对于 mongodb 2.2+ 版本,您需要将选项 multi 设置为 true 以一次更新多个文档.

db.test.update({foo: "bar"}, {$set: {test: "success!"}}, {multi: true})

对于 mongodb 3.2+ 版本,您还可以使用新方法 updateMany() 一次更新多个文档,而无需单独的 multi 选项.

For versions of mongodb 3.2+ you can also use new method updateMany() to update multiple documents at once, without the need of separate multi option.

db.test.updateMany({foo: "bar"}, {$set: {test: "success!"}})