简体   繁体   English

mongodb 从一个数组更新嵌套数组

[英]mongodb update nested array from a array

I have a array in mongodb document.我在 mongodb 文档中有一个数组。

 {
  _id: 1,
  jobs:[
   {
     _id:1,
     time: "08:00",
     status: "pending",
     user: 'user1'
   },
   {
     _id:2,
     time: "09:00",
     status: "pending",
     user: 'user1'
   },
   {
     _id:3,
     time: "07:30",
     status: "done",
     user: 'user2'
   }
]
}

now I have a updated jobs array like this.现在我有一个像这样更新的作业数组。

jobs:[
   {
     _id:1,
     time: "10:00",
     status: "done"
   },
   {
     _id:2,
     time: "11:00",
     status: "done"
   }
]

updated document should like this更新的文件应该是这样的

{
  _id: 1,
  jobs:[
   {
     _id:1,
     time: "10:00", // updated
     status: "done" // updated
     user: 'user1'
   },
   {
     _id:2,
     time: "11:00", // updated
     status: "done", // updated
     user: "user1"
   },
   {
     _id:3,
     time: "07:30",
     status: "done",
     user: 'user2'
   }
]
}

I tried using update and $set and no luck so far我尝试使用 update 和 $set 到目前为止没有运气

how do I update the only the values in the updated array in to the mongodb document?如何将更新数组中的唯一值更新到 mongodb 文档中? thanks in advance提前致谢

One option is using an update with a pipeline:一种选择是使用带有管道的更新:

  1. Add the new data into the document as newData将新数据作为newData添加到文档中
  2. Using a $map to loop over the jobs items, for each item merge it with the matching item in newData .使用$map遍历jobs项目,对于每个项目,将其与newData中的匹配项目合并。
db.collection.update(
  {_id: 1},
  [{$addFields: {
      newData: [
        {_id: 1, time: "10:00", status: "done"},
        {_id: 2, time: "11:00", status: "done"}
      ]
    }
  },
  {$project: {
      jobs: {
        $map: {
          input: "$jobs",
          in: {
            $mergeObjects: [
              "$$this",
              {$arrayElemAt: ["$newData", {$indexOfArray: ["$newData._id", "$$this._id"]}]}
            ]
          }
        }
      }
    }
  }
])

See how it works on the playground example看看它在操场上的例子是如何工作的

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

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