Skip to content
Advertisement

MongoDb update with ElemMatch

I have a collection that has document structure like following:

Mongo PlayGround

{
    "basicDetails": {
        "id": "1",
        "name": "xyz"
    },
    "tasks": [{
        "id": "10",
        "name": "task10",
        "subtasks": [{
            "id": "120",
            "name": "subTask120",
            "description": "ABC"
        }]
    }]
}

As you can see, each document has basicDetails object and a tasks array. Each task contains some properties of its own and a subtasks array.

I want to update subtasks’s description from ABC to XYZ

where root level id is 1, task'id is 10 and subTasks.id =120

How do I do so?

I know I could find correct document via:

db.collection.find({
  "basicDetails.id": "1",
  "tasks": {
    "$elemMatch": {
      "id": "10",
      "subtasks": {
        "$elemMatch": {
          "id": "120"
        }
      }
    }
  }
})

But how do I update it? I want to update only one single property of a single subtasks i.e description

Advertisement

Answer

To update nested arrays, the filtered positional operator $[identifier] identifies the array elements that match the arrayFilters conditions for an update operation.

Try the following query to $set in nested array:

db.collection.updateOne({
  "basicDetails.id": "1"
},
{
  "$set": {
    "tasks.$[tasks].subtasks.$[subtasks].description": "XYZ"
  }
},
{
  "arrayFilters": [
    {
      "tasks.id": "10"
    },
    {
      "subtasks.id": "120"
    }
  ]
})

MongoDB Playground

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement