【问题标题】:Adding a field from an object in an array to another field of an object within the same array MongoDB将数组中对象的字段添加到同一数组中对象的另一个字段MongoDB
【发布时间】:2020-11-25 10:35:52
【问题描述】:

在更新 MongoDB 中的文档方面我非常需要帮助。

所以这是我的问题。我需要删除记录数组中类型为 OLD 的对象,但是在删除它之前,我需要将它的值添加到类型为 CURRENT 的对象中。所以给出下面的例子。查询应将 CURRENT 对象的值更改为 120,并且类型为 OLD 的对象将被删除;

我无法进行两次查询,因为此查询将更新数千条数据。

这是在 node.js 中使用猫鼬。

谢谢你!

{
    name: 'Test',
    records: [
        {
            type: 'NEW',
            value: 50,
        },
        {
            type: 'OLD',
            value: 100,
        },
        {
            type: 'CURRENT',
            value: 20
        } 
    ]
}

【问题讨论】:

  • 嗯,这有点像,但这实际上不是问题。我很容易从数组中拉出或删除对象。问题是我需要在删除它之前将它添加到数组中的另一个对象

标签: node.js mongodb express mongoose nosql


【解决方案1】:

您可以使用 MongoDB v4.2 中的 update with aggregation pipeline 来完成,

  • 第一个匹配类型为CURRENT
  • 首先将$setCURRENT 类型和OLD 类型的值相加
  • 第二个$set 删除类型OLD
db.collection.updateMany(
  { "records.type": "CURRENT" },
  [{
    $set: {
      records: {
        $map: {
          input: "$records",
          as: "r",
          in: {
            $cond: {
              if: { $eq: ["$$r.type", "CURRENT"] },
              then: {
                type: "$$r.type",
                value: {
                  $add: [
                    "$$r.value",
                    {
                      $reduce: {
                        input: "$records",
                        initialValue: 0,
                        in: {
                          $cond: {
                            if: { $eq: ["$$this.type", "OLD" ] },
                            then: { $add: ["$$this.value", "$$value"] },
                            else: "$$value"
                          }
                        }
                      }
                    }
                  ]
                }
              },
              else: "$$r"
            }
          }
        }
      }
    }
  },
  {
    $set: {
      records: {
        $filter: {
          input: "$records",
          as: "r",
          cond: { $ne: ["$$r.type", "OLD"] }
        }
      }
    }
  }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2019-05-10
    • 2020-07-24
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多