Wylan Osorio
Wylan Osorio

Reputation: 1166

Update all documents that matched a list of ids in one command

Is there a way to update all documents that matched a list of id's in just one command.

Currently I have to loop each id to update

var ids = [
  "8007068113729",
  "8007068502622",
  "8007068505821",
  "0825646209804",
  "0880319084614",
  "4260041334885"
]

ids.forEach(function(i){
    db.listing.update({_id:i},{$set:{Supplier:'S'}});
});

Upvotes: 3

Views: 3951

Answers (2)

Tan Le
Tan Le

Reputation: 187

I think you can use $in operator with multi flag as this :

var ids = [
  "8007068113729",
  "8007068502622",
  "8007068505821",
  "0825646209804",
  "0880319084614",
  "4260041334885"
]

db.listing.update({_id:{ $in: ids}},{$set:{Supplier:'S'}}, {multi: true});

Hope that help !

Upvotes: 1

Sede
Sede

Reputation: 61263

Simply use the updateMany method and the $in operator.

var ids = [
  "8007068113729",
  "8007068502622",
  "8007068505821",
  "0825646209804",
  "0880319084614",
  "4260041334885"
]

db.listing.updateMany({ "_id": { "$in": ids }}, { "$set": { "Supplier": "S" }});

Upvotes: 9

Related Questions