1

I want to update an existing item inside of an array in an array.

The structure of my document looks like the following:

    {
  "_id":"a1",
  "projects":[{
    "_id": "b1",
    "title":"Title A",
    "task":[
           {"_id": "c1",
            "title":"Title B"},
            {"_id": "c2",
            "title":"Title C"},
            {"_id": "c3",
            "title":"Title D"}
          ],

}]
}

Let's say we want to change the "task" :

{"_id": "c2",
 "title":"Title C"}

to

{"_id": "c2",
 "title":"Title C1"}

Does someone know a proper way to update this subdocument?

1 Answer 1

1

By using a combination of $set with the posititonal operator and arrayFilters, this should be doable:

db.getCollection('so-test').updateOne(
   { _id: "a1"},
   { $set: { "projects.$[].task.$[task].title": "Title C1" } },
   { arrayFilters: [  {"task.title": "Title C"} ]}
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.