简体   繁体   中英

How to update multiple documents with multiple condtions in MongoDB?

I have a MongoDB collections with various documents. Now I have the input document Ids in an array of cars which I want to update. 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.

Now one way to update cars is to have an async.each applied on the array and an aysnc.each on these two documents. 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. I have already gone through several pages and still haven't found anything wanted to know if this is possible in mongo or not?

At first you may need to convert your car ids String type to mongodb ObjectId that means like:

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

then use $in operator to match with documents.

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. 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.

See $in-doc to know more about the uses.

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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