【问题标题】:How to group and count value of item in array如何对数组中项目的值进行分组和计数
【发布时间】:2023-02-16 18:01:53
【问题描述】:
[
  {
    providers: [
      {
        code: 1
      },
      {
        code: 1
      },
    ]
  },
  {
    providers: [
      {
        code: 2
      },
      {
        code: 1
      },
      {
        code: 2
      }
    ]
  },
]

我有这样的文件

并希望获得如下结果:

[
  {
    "code": 1,
    "total": 2 (because it appear in two item of the array)
  },
  {
    "code": 2,
    "total": 1 (because it appear in just the second item of the array)
  }
]

我尝试使用 $sum: 1 展开数组和分组,但是当展开时,总数会增加,这不是我想要的。请帮我。

【问题讨论】:

    标签: aggregation-framework


    【解决方案1】:

    你有一个好主意,你只需要将你的 code 数组转换为 $setIntersection 设置。

    见 mongoplayground https://mongoplayground.net/p/NwVcO9iBXAf

    db.collection.aggregate([
      {
        $set: {
          providers: {
            "$setIntersection": "$providers"
          }
        }
      },
      {
        "$unwind": "$providers"
      },
      {
        "$group": {
          "_id": "$providers.code",
          "count": {
            "$sum": 1
          }
        }
      },
      {
        $project: {
          _id: 0,
          code: "$_id",
          total: "$count"
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2020-04-25
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多