mustafa shaikh
mustafa shaikh

Reputation: 71

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

I have the following documents in my candidate 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'
  }
]

I want to group by age and city fields and count the documents based on its sum independent of each other I tried following query

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

which gives me count of combine results of age and city. what I want instead

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

thanks for any help.

Upvotes: 0

Views: 22

Answers (1)

matthPen
matthPen

Reputation: 4343

You need to use $facet stage, with a $group stage per age, and another per city. Here's the query :

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

Upvotes: 2

Related Questions