Mongodb通过id更新嵌套数组

时间:2018-04-07 18:17:28

标签: mongodb

我有以下文档,想要更新state

文件编号:ObjectId(“5a4e5a448b70d50e34d204a5”)

目标ID:ObjectId(“5a4e5a438b70d50e34d203ea”)

我不知道如何将状态更新为例如4

  {
  "_id" : ObjectId("5a4e5a448b70d50e34d204a5"),
  "name" : "Wirtschaftsdienst",
  "date" : ISODate("2012-10-07T00:00:00.000Z"),
  "comment" : null,
  "tasks" : [ 
      {
          "name" : "Speisen und Getränke",
          "sections" : [ 
              {
                  "start" : 46800,
                  "end" : 72000,
                  "entirely" : true,
                  "assistants" : [ 
                      {
                          "assistant" : {
                              "_id" : ObjectId("5a4e5a438b70d50e34d203ea")
                          },
                          "state" : 3
                      }, 
                      {
                          "assistant" : {
                              "_id" : ObjectId("5a4e5a438b70d50e34d203f4")
                          },
                          "state" : 3
                      }
                  ]
              }
          ]
      }
  ]
 }

1 个答案:

答案 0 :(得分:1)

使用位置操作符$[]arrayFilters来完成工作!

尝试此查询:

db.collection.update(
 {"_id" : ObjectId("5a4e5a448b70d50e34d204a5")},
 {$set: {"tasks.$[].sections.$[].assistants.$[element].state":4}},
 {arrayFilters: [ {"element.assistant":{"_id" : 
  ObjectId("5a4e5a438b70d50e34d203ea")} } 
  ], multi:true}
)

输出是:

/* 1 */
{
"_id" : ObjectId("5a4e5a448b70d50e34d204a5"),
"name" : "Wirtschaftsdienst",
"date" : ISODate("2012-10-07T00:00:00.000Z"),
"comment" : null,
"tasks" : [ 
    {
        "name" : "Speisen und Getränke",
        "sections" : [ 
            {
                "start" : 46800,
                "end" : 72000,
                "entirely" : true,
                "assistants" : [ 
                    {
                        "assistant" : {
                            "_id" : ObjectId("5a4e5a438b70d50e34d203ea")
                        },
                        "state" : 4.0
                    }, 
                    {
                        "assistant" : {
                            "_id" : ObjectId("5a4e5a438b70d50e34d203f4")
                        },
                        "state" : 3.0
                    }
                ]
            }
        ]
    }
 ]
}