Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

413
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
});
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!