简体   繁体   中英

MongoDB Update Item in Array inside Array

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM