【问题标题】:How to create MongoDB Update query to update certain elements in an array of objects如何创建 MongoDB 更新查询以更新对象数组中的某些元素
【发布时间】:2020-06-23 02:17:07
【问题描述】:

我有一个包含数千个文档的 mongodb 集合。我在这个集合中有不同的步骤,它们的步骤状态已完成。我想将特定步骤状态从已完成更新为打开。例如,我只想将第三步和第四步的状态更新为“打开”,并将文件 overAllStatus 更新为已启动。我想在“executionId”为“20200622104036256”的情况下执行此操作。

我的文档/json 结构。集合名称 order_status

   {
  "_id" : ObjectId("5ef03d8f5f5775000921e5b9"),
  "executionId" : "20200622104036256",
  "stateNumber" : "123456",
  "overAllStatus" : "Completed",
  "steps" : [{
      "name" : "Step One",
      "status" : "Completed"
    }, {
     "name" : "Step Two",
      "status" : "Completed"
    }, {
     "name" : "Step Three",
       "status" : "Completed"
    }, {
     "name" : "Step Four",
       "status" : "Completed"
    }],
  "ABC" : {
    "status" : "Completed"
  }
  
}

在我执行 shell 更新脚本/查询之后。 “executionId”为“20200622104036256”的所有文档如下所示

{
  "_id" : ObjectId("5ef03d8f5f5775000921e5b9"),
  "executionId" : "20200622104036256",
  "stateNumber" : "123456",
  "overAllStatus" : "Started",
  "steps" : [{
      "name" : "Step One",
      "status" : "Completed"
    }, {
     "name" : "Step Two",
      "status" : "Completed"
    }, {
     "name" : "Step Three",
       "status" : "Open"
    }, {
     "name" : "Step Four",
       "status" : "Open"
    }],
  "ABC" : {
    "status" : "Completed"
  }
  
}

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    查询:

    /** Using updateMany to update multiple documents matching certain criteria */
    db.order_status.updateMany(
      { executionId: "20200622104036256" }, // Filtering for specific docs
      { $set: { overAllStatus: "Started", "steps.$[element].status": "Open" } }, // Update specific element in an array
      { arrayFilters: [{ "element.name": { $in: ["Step Three", "Step Four"] } }] } // Returns specific elements in `steps` array that matches criteria for update
    );
    

    参考: arrayfilters-for-an-array-update-operations

    注意:

    如果您只想在以下情况下更新overAllStatus 字段,对于带有executionId: "20200622104036256" 并且至少有一个名称为“第三步”或“第四步”的步骤元素 - 那么您的过滤器部分是@ 987654325@ 应该是:

    {"executionId" : "20200622104036256", 'steps.name': { $in : ["Step Three","Step Four"]}}
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2023-02-13
      • 2020-07-09
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多