如何更新 mongodb 中的对象数组?

How to update array of objects in mongodb?

不知道以前有没有人问过这个问题。但是,我需要问这个以获得你们的帮助:

我有如下文件:

{
    "taskboard_id": "6149a3de8f604511e6883bae",
    "user_id": "61399af5d6294f56aa1116f0",
    "task_groups": [{
        "task_group_id": "614975a0e8fad7ef68561b36",
        "task_id": "614869a706ff00ab459460e5",
        "is_completed": true,
        "completion_date":"2021-10-07T05:04:50.760Z",
    },
    {
        "task_group_id": "614975a0e8fad7ef68561b37",
        "task_id": "614869a706ff00ab459460e5",
        "is_completed": false,
        "completion_date":"",
    }]
}

两个对象数组的区别在于task_group_id。 现在我想通过 taskboard_iduser_id"task_groups.task_group_id""task_groups. task_id" 更新 is_completedcompletion_date。下面是我的查询:

db.task_status.updateOne(
{
        user_id: new ObjectId(payload.user_id),
        taskboard_id: new ObjectId(payload.taskboard_id),
        "task_groups.task_group_id": new ObjectId(payload.task_group_id),
        "task_groups.task_id": new ObjectId(payload.task_id),
 },
 $set: {
          "task_groups.$.is_completed": payload.is_completed,
          "task_groups.$.completion_date": new Date(),
 },
);

问题是,每当我尝试更新第一个对象时,第一个对象都可以正常更新,但每当涉及到第二个对象时,它就不会更新。 谁能帮我解决这个问题?

update

中使用arrayfilter
db.collection.update({
  user_id: "61399af5d6294f56aa1116f0",
  taskboard_id: "6149a3de8f604511e6883bae",
  "task_groups.task_group_id": "614975a0e8fad7ef68561b37",
  "task_groups.task_id": "614869a706ff00ab459460e5",
  
},
{
  "$set": {
    "task_groups.$[item].is_completed": true,
    "task_groups.$[item].completion_date": new Date(),
    
  }
},
{
  arrayFilters: [
    {
      "item.task_group_id": {
        $eq: "614975a0e8fad7ef68561b37"
      },
      "item.task_id": {
        $eq: "614869a706ff00ab459460e5"
      }
    }
  ],
  multi: true
})

mongoplayground