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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.