首页 > 解决方案 > 如何在mongoDB聚合中循环数组对象并按条件重新赋值?

问题描述

我对 mongo 聚合有疑问,请帮忙。

首先,我有一个这样的集合:

{
 "id": 1,
 "properties": [
   {
       key: "prop1",
       value: "propVal1",
   },
   {
       key: "prop2",
       value: "propVal2",
   },
   {
       key: "prop3",
       value: "propVal3",
   }
]

还有一个像这样的 JS 对象:

const newKeyValues = [{ key: "prop1" , value: "newVal1" }, { key: "prop2" , value: "newVal2" }];

那么如何创建一个聚合管道来通过键设置新值到properties数组?管道的预期输出是这样的:

{
 "id": 1,
 "properties": [
   {
       key: "prop1",
       value: "newVal1",
   },
   {
       key: "prop2",
       value: "newVal2",
   },
   {
       key: "prop3",
       value: "propVal3",
   }
]

谢谢大家。

标签: mongodbmongodb-queryaggregation-framework

解决方案


我想我找到了答案,需要另一个 JS 函数来映射值key。但是查询是基于以下内容构建的:

db.collection.aggregate({
  $project: {
    id: "$id",
    properties: {
      $map: {
        input: "$properties",
        as: "properties",
        in: {
          key: "$$properties.key",
          value: {
            $switch: {
              branches: [
                {
                  case: {
                    $eq: [
                      "$$properties.key",
                      "prop1"
                    ]
                  },
                  then: "newValue1"
                },
                {
                  case: {
                    $eq: [
                      "$$properties.key",
                      "prop2"
                    ]
                  },
                  then: "newValue2"
                }
              ],
              default: "$$properties.value"
            }
          }
        }
      }
    }
  }
})

推荐阅读