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

在对多个字段mongodb聚合进行分组时,如何获取saperated计数?,mongodb,aggregation-framework,aggregation,Mongodb,Aggregation Framework,Aggregation,我的候选人收藏中有以下文件 candidates = [ { name: "amit", age: 21, city: 'pune' } { name: "rahul", age: 23, city: 'pune' }, { name: "arjun", age: 21, city: 'pune' }, { name: "rakesh", age: 23, city:

我的候选人收藏中有以下文件

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 stage,每个年龄段有$group stage,每个城市有一个$group stage。 问题是:

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
        }
      ]
    }
  },
])

您需要使用$facet stage,每个年龄段有$group stage,每个城市有一个$group stage。 问题是:

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
        }
      ]
    }
  },
])