Home > Software engineering >  How Can I Update Nested Array Element By Id
How Can I Update Nested Array Element By Id

Time:03-01

I'm new to mongodb , I want to update nested array element by id with findOneAndUpdate

const Data = {
   items : [
      {
       id: 1,
       name : "a",
       child : [
         { id : 11, name "aa"},
         { id : 12, name "bb"},
        ]
      },
      {
       id: 2,
       name : "b",
       child : [
         { id : 22, name "ba"},
         { id : 23, name "bb"},
        ]
      },
    ]
}

CodePudding user response:

This is how you can do via arrayFilters:

 db.collection.update({},
  {
    $set: {
    "items.$[y].child.$[x].name": "cc"
    }
  },
  {
    arrayFilters: [
     {
      "x.id": 11
     },
     {
      "y.id": 1
     }
   ]
 })

Explained: You specify which element you need to update via arrayFilter x and y , in the example this array element with id:11 in x and id:1 in y. In the update operation you provide the new value for field name , in the example this is value "cc"

playground

  • Related