1

Trying to update the nested object for the document in MongoDB.

{
    "items" : [
      {
        "id": 1,
        "name": "a",
        "child": [
          { "id": 11, "name": "aa" },
          { "id": 12, "name": "bb" },
         ]
      },
    ]
}

Need to update the child id to 13 whose name is "aa".

O/P, which I am trying to get

{
    "items" : [
      {
        "id": 1,
        "name": "a",
        "child": [
          { "id": 13, "name": "aa" },
          { "id": 12, "name": "bb" },
        ]
      },
    ]
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Sushil
  • 121
  • 1
  • 7

1 Answers1

1

Work with $[<identifier>] filtered positional operator and arrayFilters.

db.collection.update({
  "items.child.name": "aa"
},
{
  $set: {
    "items.$[].child.$[c].id": 13
  }
},
{
  arrayFilters: [
    {
      "c.name": "aa"
    }
  ]
})

Sample Mongo Playground

Yong Shun
  • 35,286
  • 4
  • 24
  • 46