【问题标题】:How to combine find and update to 1 update如何将查找和更新合并为 1 个更新
【发布时间】:2022-01-23 21:40:04
【问题描述】:

我正在使用 Spring Data MongoTemplate,试图优化 mongodb 更新。我可以在没有find() 的情况下仅进行1 次更新以首先检查数据库中文档的status

  • 如果状态不是“已阻止”,请更新状态并添加到 行动。
  • 如果状态为“已阻止”,只需添加到操作中,而不是更新到状态。
Java object to update:
status: "Display",
action: "Show"

mongodb:
{
    status: "Blocked",
    actions: [
        "Show",
        "Hide",
        "Show",
        ...
    ]
}

【问题讨论】:

  • @ray 我希望始终更新操作属性以保持跟踪。谢谢,现在我知道 Mongo 游乐场了!
  • 新动作在数组中的第一个位置只有 1 个小东西。
  • 这就是我想要的,非常感谢您的快速回复!

标签: java mongodb mongodb-query spring-data-mongodb


【解决方案1】:

您可以使用聚合管道进行更新。对$addFields 阶段的状态字段进行条件检查。

db.collection.update({},
[
  {
    "$addFields": {
      "userInput": {
        status: "Display",
        action: "Show"
      }
    }
  },
  {
    "$addFields": {
      "status": {
        "$cond": {
          "if": {
            $ne: [
              "$status",
              "Blocked"
            ]
          },
          "then": "$userInput.status",
          "else": "Blocked"
        }
      },
      actions: {
        "$concatArrays": [
          [
            "$userInput.action"
          ],
          "$actions"
        ]
      }
    }
  },
  {
    "$unset": "userInput"
  }
],
{
  multi: true
})

这里是Mongo playground 供您参考。

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2020-12-07
    相关资源
    最近更新 更多