【问题标题】:How to update array of objects in mongodb?如何更新 mongodb 中的对象数组?
【发布时间】:2021-10-07 14:39:30
【问题描述】:

我不知道以前是否有人问过这个问题。但是,我需要向你们寻求帮助:

我有如下文件:

{
    "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(),
 },
);

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

【问题讨论】:

  • 你检查过$[]操作符是否是你要找的吗?
  • @ray 它正在更新所有对象...

标签: node.js mongodb nosql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2021-09-27
    • 2023-01-12
    相关资源
    最近更新 更多