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?

J.F.
  • 13,927
  • 9
  • 27
  • 65
Karrar
  • 1,273
  • 3
  • 14
  • 30

1 Answers1

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 */
  );
})
Ezra Siton
  • 6,887
  • 2
  • 25
  • 37