Updating Nested array object Document In MongoDB using Pymongo

Viewed 21

Trying to update in MongoDB nested object Document

   "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"},
        ]
      },
    ]
}
1 Answers

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

Related