MongoDB:如何使用单个命令更新多个文档? [英] MongoDB: How to update multiple documents with a single command?

查看:36
本文介绍了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!"}})

这篇关于MongoDB:如何使用单个命令更新多个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆