Mongodb multi update with different value

2019-08-13 17:27发布

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 .

2条回答
你好瞎i
2楼-- · 2019-08-13 18:04

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 }
      }
    })
  )
})
查看更多
看我几分像从前
3楼-- · 2019-08-13 18:11

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.

查看更多
登录 后发表回答