如何在对多个字段 mongodb 聚合进行分组时获得分离计数?

How Do I get saperated counts while grouping on multiple fields mongodb aggregation?

我的候选人中有以下文件 collection。

candidates = [
  {
    name: "amit",
    age: 21,
    city: 'pune'
  }
   {
    name: "rahul",
    age: 23,
    city: 'pune'
  },
   {
    name: "arjun",
    age: 21,
    city: 'pune'
  },
   {
    name: "rakesh",
    age: 23,
    city: 'pune'
  },
  {
    name: "amit",
    age: 22,
    city: 'nashik'
  }
]

我想按年龄和城市字段分组,并根据其总和计算文档,彼此独立 我尝试了以下查询

candidate.aggregate([
  {$group: {_id: {age: '$age', city: '$city'}, count: {$sum: -1}}}
  {$sort: {count: -1}},
  {$limit: 10}
])

这给了我年龄和城市的综合结果。 我想要什么

{
  ages: [
    {
      age: 21,
      count: 2
    },
    {
      age: 23,
      count: 2
    },
    {
      age: 21,
      count: 1
    }
  ],
  cities: [
    {
      city: 'pune',
      count: 4
    },
    {
      city: 'nashik',
      count: 1
    }
  ]
}

感谢您的帮助。

您需要使用 $facet 阶段,每个年龄段一个 $group 阶段,每个城市另一个阶段。 这是查询:

db.collection.aggregate([
  {
    $facet: {
      byCity: [
        {
          $group: {
            _id: {
              city: "$city"
            },
            count: {
              $sum: 1
            }
          }
        },
        {
          $sort: {
            count: -1
          }
        },
        {
          $limit: 10
        }
      ],
      byAge: [
        {
          $group: {
            _id: {
              age: "$age",

            },
            count: {
              $sum: 1
            }
          }
        },
        {
          $sort: {
            count: -1
          }
        },
        {
          $limit: 10
        }
      ]
    }
  },
])

Mongo playground