1

I'm trying to update a field inside array of fields in mongodb. in this below structure, i want to change the values of subItems which its value field = item1 to be item instead.

here's the structure

{
  item: {...},
  item: {
    _id: ObjectId("234"),
    subItems: [
      {
        _id: ObjectId("123"),
        value: "item1",
        name: "item1"
      },
      {
        _id: ObjectId("435"),
        value: "item2",
        name: "item2"
      }
    ]
  }
}

I wrote code to do a bulkwrite

await db.collection('items').find({}).forEach((items) => {
  items.subItems.forEach((item) => {
    if (item.value === 'item1') {
      console.log(items._id);
      bulkOps.push({
        updateOne: {
          filter: { value: 'item1' },
          update: { $set: { value: 'item', name: 'item' } },
        },
      });
    }
  });
});

In this array bulkOps i got the updateOne sentences of what i need, my question how to apply this to the database?

Zeyad Etman
  • 2,250
  • 5
  • 25
  • 42
  • 1
    you don't even have to do a bulkWrite for this, you can just do an update query using $ path match syntax to update only the array items which match the condition. – r3wt Jan 04 '21 at 15:20
  • could you describe an example or such send me a reference for that? @r3wt – Zeyad Etman Jan 04 '21 at 15:25
  • 1
    From the marked duplicate, your update operation should be of the form `await db.collection('items').update( { "subItems.value": "item1" }, { "$set": { "subItems.$[elem].value": "item", "subItems.$[elem].name": "item" } }, { "arrayFilters": [{ "elem.value": "item1" }], "multi": true } )` – chridam Jan 04 '21 at 15:36

0 Answers0