Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

412
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda