在 MongoDB 聚合中按关联删除动态字段

Removing Dynamic Fields by Association in MongoDB Aggregation

我正在尝试通过 react chartjs 显示 MongoDB 聚合结果。在聚合中,我可以通过集合运算符删除一个值为静态的字段。有没有办法通过值是动态的关联删除第二个字段?在下面的示例中,{"A": "N"} 表示设置运算符可以轻松删除的字段,而 {"A_count":1} 表示我要删除的相应动态字段。

开始聚合输出

[{
  "_id":"Fubar",
  "A_set":[{"A":"Y"},{"A":"N"}],
  "A_count_set":[{"A_count":0},{"A_count":1}]
}]

设置静态字段移除操作

{$set: {
  A_set: {
    $filter: {
      input: "$A_set",
      as: "x",
      cond: { "$ne": [ "$$x", {"A":"N"}] }
    }
  }
}}

当前聚合输出

[{
  "_id":"Fubar",
  "A_set":[{"A":"Y"}],
  "A_count_set":[{"A_count":0},{"A_count":1}]
}]

目标聚合输出

[{
  "_id":"Fubar",
  "A_set":[{"A":"Y"}],
  "A_count_set":[{"A_count":0}]
}]
  • $project合并两个位置相同的数组
  • $set 过滤数组
  • $addFields恢复原数组
  • $project删除合并数组

汇总

db.collection.aggregate([
  {
    $project: {
      anotherValue: {
        $map: {
          input: {
            $range: [
              0,
              {
                $size: "$A_set"
              }
            ]
          },
          as: "idx",
          in: {
            $mergeObjects: [
              {
                $arrayElemAt: [
                  "$A_set",
                  "$$idx"
                ]
              },
              {
                $arrayElemAt: [
                  "$A_count_set",
                  "$$idx"
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      anotherValue: {
        $filter: {
          input: "$anotherValue",
          as: "x",
          cond: {
            "$ne": [
              "$$x.A",
              "N"
            ]
          }
        }
      }
    }
  },
  {
    $addFields: {
      "A_set": {
        $map: {
          input: "$anotherValue",
          as: "a",
          in: {
            "A": "$$a.A"
          }
        }
      },
      "A_count_set": {
        $map: {
          input: "$anotherValue",
          as: "a",
          in: {
            "A_count": "$$a.A_count"
          }
        }
      }
    }
  },
  {
    "$project": {
      "anotherValue": 0
    }
  }
])

mongoplayground