简体   繁体   English

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

[英]MongoDB: How to update multiple documents with a single command?

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?有没有更好的办法?

Multi update was added recently, so is only available in the development releases (1.1.3).最近添加了多更新,因此仅在开发版本 (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:在 shell 中,您通过将true作为第四个参数传递给update()来执行多重更新,其中第三个参数是 upsert 参数:

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

For versions of mongodb 2.2+ you need to set option multi true to update multiple documents at once.对于 mongodb 2.2+ 版本,您需要设置选项 multi true 以一次更新多个文档。

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

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

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

Starting in v3.3 You can use updateMany从 v3.3 开始,您可以使用 updateMany

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

In v2.2, the update function takes the following form:在 v2.2 中,更新函数采用以下形式:

 db.collection.update(
   <query>,
   <update>,
   { upsert: <boolean>, multi: <boolean> }
)

https://docs.mongodb.com/manual/reference/method/db.collection.update/ https://docs.mongodb.com/manual/reference/method/db.collection.update/

For Mongo version > 2.2 , add a field multi and set it to true对于Mongo version > 2.2 ,添加一个字段 multi 并将其设置为 true

db.Collection.update({query}, 
                 {$set: {field1: "f1", field2: "f2"}},
                 {multi: true })

I've created a way to do this with a better interface.我已经创建了一种使用更好的界面来做到这一点的方法。

  • db.collection.find({ ... }).update({ ... }) -- multi update db.collection.find({ ... }).update({ ... }) -- 多更新
  • db.collection.find({ ... }).replace({ ... }) -- single replacement db.collection.find({ ... }).replace({ ... }) -- 单个替换
  • db.collection.find({ ... }).upsert({ ... }) -- single upsert db.collection.find({ ... }).upsert({ ... }) -- 单个 upsert
  • db.collection.find({ ... }).remove() -- multi remove db.collection.find({ ... }).remove() -- 多删除

You can also apply limit, skip, sort to the updates and removes by chaining them in beforehand.您还可以通过预先链接更新和删除来应用限制、跳过、排序。

If you are interested, check out Mongo-Hacker如果您有兴趣,请查看Mongo-Hacker

In the MongoDB Client, type:在 MongoDB 客户端中,键入:

db.Collection.updateMany({}, $set: {field1: 'field1', field2: 'field2'})

New in version 3.2 3.2 版的新功能

Params::参数::

{}:  select all records updated

Keyword argument multi not taken未采用multi关键字参数

MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.当您发出更新命令时,MongoDB 只会找到一个与查询条件匹配的匹配文档,首先匹配的文档恰好会被更新,即使有更多符合条件的文档也将被忽略。

so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria.所以为了克服这个问题,我们可以在更新语句中指定“MULTI”选项,这意味着更新所有符合查询条件的文档。 scan for all the documnets in collection finding those which matches the criteria and update :扫描集合中的所有文档,找到符合条件的文档并更新:

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

The following command can update multiple records of a collection以下命令可以更新一个集合的多条记录

db.collection.update({}, 
{$set:{"field" : "value"}}, 
{ multi: true, upsert: false}
)

To Update Entire Collection,要更新整个集合,

db.getCollection('collection_name').update({},
{$set: {"field1" : "value1", "field2" : "value2", "field3" : "value3"}},
{multi: true })

I had the same problem , and i found the solution , and it works like a charm我遇到了同样的问题,我找到了解决方案,它就像一个魅力

just set the flag multi to true like this :只需像这样将标志 multi 设置为 true :

 db.Collection.update(
                {_id_receiver: id_receiver},
               {$set: {is_showed: true}},
                {multi: true}   /* --> multiple update */
            , function (err, updated) {...});

i hope that helps :)我希望有帮助:)

所有最新版本的 mongodb updateMany()工作正常

db.getCollection('workers').updateMany({},{$set: {"assignedVehicleId" : "45680"}});

You can use.`你可以使用。`

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "abc@gmail.com",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  `

The updateMany() method has the following form: updateMany() 方法具有以下形式:

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

The restaurant collection contains the following documents:餐厅集合包含以下文件:

{ "_id" : 1, "name" : "Central Perk Cafe", "violations" : 3 }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "violations" : 2 }
{ "_id" : 3, "name" : "Empire State Sub", "violations" : 5 }
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "violations" : 8 }

The following operation updates all documents where violations are greater than 4 and $set a flag for review:以下操作更新所有违规大于 4 的文档并 $set a flag 以供审查:

try {
   db.restaurant.updateMany(
      { violations: { $gt: 4 } },
      { $set: { "Review" : true } }
   );
} catch (e) {
   print(e);
}

Thanks for sharing this, I used with 2.6.7 and following query just worked,感谢分享这个,我用 2.6.7 和以下查询刚刚工作,

for all docs:对于所有文档:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:true})

for single doc:对于单个文档:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:false})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM