Reputation: 12945
I have multiple document to update in mongodb , each document has to be updated with different value . Values to update is available in a JSON array .
{_id :1 ,name :'A','place':'London'},
{_id :2 ,name :'B','place':'UK'},
{_id :3 ,name :'C','place':'USA'},
{_id :4 ,name :'D','place':'CANADA'},
{_id :5 ,name :'E','place':'India'}
JSON array to update :
[{_id :1 ,name :'l','place':'Indonesia'},{_id :2 ,name :'B','place':'UAE'}]
I have to update _id 1,2 of my collection with new value in json array . How can I do it without iterating json array and in one query .
Upvotes: 1
Views: 3384
Reputation: 2343
If you are using mongoose then you could try bulkWrite method. BulkWrite sends only one request to mongo. The code would look something like this:
const itemsToUpdate = [
{ _id: ObjectId('5c6bd4c8716adf072955e855'), status: 'pending' },
{ _id: ObjectId('5c6bd4c8716adf072955e777'), status: 'done' },
];
Model.bulkWrite(
itemsToUpdate.map((item) =>
({
updateOne: {
filter: { _id: item._id },
update: { $set: item }
}
})
)
})
Upvotes: 3
Reputation: 26012
No, you cannot update multiple documents with different values in a single query. You have to iterate through json array and update each document separately.
Upvotes: 2