简体   繁体   English

如何在MongoDB中使用多个条件更新多个文档?

[英]How to update multiple documents with multiple condtions in MongoDB?

I have a MongoDB collections with various documents. 我有一个包含各种文档的MongoDB集合。 Now I have the input document Ids in an array of cars which I want to update. 现在,我在要更新的汽车阵列中有输入文档ID。 Something like this. 这样的事情。

req.body = 
{ cars: [ '584cf6c126df866138a29408', '5852819e9693c27c136104bd' ],
    name: 'Home' },
{ cars: [ '584d638242795854a091cbbf', '5842e09e372b786355ba50e7' ],
    name: 'Office' } ]

Expected Operation 预期运作

db.cars.update({_id : req.body[i].cars}, {name : req.body[i].name}, {new : true});

Expected Result 预期结果
All four documents with ids are updated with their name field in the document. 具有ID的所有四个文档都将在文档中使用其名称字段进行更新。

Now one way to update cars is to have an async.each applied on the array and an aysnc.each on these two documents. 现在更新汽车的一种方法是在数组上应用async.each,在这两个文档上应用aysnc.each。 That's the longer way of doing it. 那是更长的方法。 I was hoping if I have one async.each for these two arrays and somehow could cramp both the documents in a single query it would make the code look more elegant. 我希望如果我对这两个数组有一个async.each,并且以某种方式可以使两个文档都局限在一个查询中,这会使代码看起来更优雅。 I have already gone through several pages and still haven't found anything wanted to know if this is possible in mongo or not? 我已经浏览了好几页,仍然找不到想要知道的在mongo中是否可行的东西?

At first you may need to convert your car ids String type to mongodb ObjectId that means like: 首先,您可能需要将汽车ID String类型转换为mongodb ObjectId ,这意味着:

cars: [ ObjectId'584cf6c126df866138a29408'), ObjectId'5852819e9693c27c136104bd') ]

then use $in operator to match with documents. 然后使用$in运算符与文档匹配。

can try this. 可以试试看

var ObjectId = require('mongodb').ObjectID;
var cars = req.body[i].cars.map(function (id) {
  return new ObjectId(id);
})

db.cars.update({_id : {$in: cars}}, 
  {$set : {name : req.body[i].name}},
  {multi : true},
  function(err, docs) {
    console.log(docs);
});

Try using $in of mongodb in find query while doing update. 进行更新时,尝试在查找查询中使用mongodb的$in See query below: 请参阅下面的查询:

Model.update({_id : {$in: req.body[i].cars}}, 
 {$set : {name : req.body[i].name}},
 {multi : true});

So this way you have to run 2 queries to update the names. 因此,这种方式必须运行2个查询来更新名称。

See $in-doc to know more about the uses. 请参阅$ in-doc以了解有关用途的更多信息。

Hope this will help you. 希望这会帮助你。

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

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