简体   繁体   English

MongoDb 使用 ElemMatch 更新

[英]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.如您所见,每个文档都有 basicDetails object 和一个 tasks 数组。 Each task contains some properties of its own and a subtasks array.每个任务都包含它自己的一些属性和一个子任务数组。

I want to update subtasks's description from ABC to XYZ我想将子任务的描述从ABC更新为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 ie description我只想更新单个子任务的一个属性,即描述

To update nested arrays, the filtered positional operator $ [identifier] identifies the array elements that match the arrayFilters conditions for an update operation.要更新嵌套的 arrays,过滤位置运算符 $ [identifier]标识与更新操作的arrayFilters条件匹配的数组元素。

Try the following query to $set in nested array:尝试以下查询以在嵌套数组中$set

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

MongoDB Playground MongoDB 游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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