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

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

问题描述:

我很惊讶地发现以下示例代码仅更新单个文档:

I was surprised to find that the following example code only updates a single document:

> db.test.save({"_id":1, "foo":"bar"});
> db.test.save({"_id":2, "foo":"bar"});

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

> db.test.find({"test":"success!"}).count();
1

我知道我可以循环浏览并不断更新,直到它们都被更改为止,但这似乎效率很低.有更好的方法吗?

I know I can loop through and keep updating until they're all changed, but that seems terribly inefficient. Is there a better way?

最近添加了多个更新,因此仅在开发版本(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!"}})