0

I have the following document schema:

let document = {
    _id: 'a1',
    name: 'some_name',
    items: [{
            _id: 1,
            name: 'item1',
        },
        {
            _id: 2,
            name: 'item2',
        },
        {
            _id: 3,
            name: 'item3',
        },
        {
            _id: 4,
            name: 'item4',
        },
    ]
}

and the following update payload is a list of documents

let updates = [{
        _id: 1,
        name: 'item11',
    },
    {
        _id: 2,
        name: 'item22',
    },
    {
        _id: 3,
        name: 'item33',
    },
    {
        _id: 4,
        name: 'item44',
    },
]

I want to update each item in the collection with the item in the update payload that has the same _id

How can I do this?

1 Answer 1

1

This is a too specific update related to each unique _id (So updateMany will not work - this is not "many" each _id is unique). Maybe related: MongoDB: update every document on one field

In your case, it is like running 4 times updateOne (And each time change the name to some value).

One option is to use bulkWrite:

https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/

db.myCollection.bulkWrite([
      { updateOne : {
         "filter" : { "_id" : "1" },
         "update" : { $set : { "name" : "item11" } }
      },
      { updateOne : {
         "filter" : { "_id" : "2" },
         "update" : { $set : { "name" : "item22" } }
      }
]);

The other option is to use plain Javascript (And map or for) and for each item in the array updateOne.

Outline only (You should test this concept under MongoDB playground).

updates.map(function(item) {
  console.log(item._id); // 1 2 3 4
  console.log(item.name); // item11 item22 item33 item44
  db.myCollection.updateOne(
    { "_id" : item._id  }, /* filter */
    { $set: { "_id" : item.name } } /* update */
  );
})
Sign up to request clarification or add additional context in comments.

1 Comment

I suppose one could use javascript to build the payload for bulkWrite then use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.