【问题标题】:Removing Dynamic Fields by Association in MongoDB Aggregation在 MongoDB 聚合中通过关联删除动态字段
【发布时间】:2021-11-16 15:05:33
【问题描述】:

我正在尝试通过 react chartjs 显示 MongoDB 聚合结果。在聚合中,我可以通过 set 运算符删除一个值为静态的字段。有没有办法通过值是动态的关联删除第二个字段?在下面的示例中,{"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}]
}]

【问题讨论】:

  • 根据什么标准删除了{"A_count":1}?例如,您想删除任何值为 1 的成员?还是其他原因?
  • 我猜你想以 tuple 的方式删除元素(即删除A_count: 1,因为它是A:N的对应元素。如果是这样的话,您的架构对于此类操作相当不方便,因为您应该将它们以元组方式放置。
  • @ray 点已拍摄。对于这个用例,似乎使用 mysql 可以让我头疼

标签: node.js reactjs mongodb aggregation-framework chart.js


【解决方案1】:
  • $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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多