Stack Exchange
Multiple group in aggregate
In my db there are two types of sessions - "studio", "classroom". I want the count of number of studio sessions and number of classroom sessions AND count of subjects in a classroom session and count of subjects in studio session.
Eg data:
    [
  {
    "key": 1,
    "type": "studio",
    "sub": "english"
  },
  {
    "key": 2,
    "type": "studio",
    "sub": "history"
  },
  {
    "key": 3,
    "type": "classroom",
    "sub": "english"
  },
  {
    "key": 4,
    "type": "studio",
    "sub": "english"
  },
  {
    "key": 5,
    "type": "classroom",
    "sub": "english"
  },
  {
    "key": 5,
    "type": "classroom",
    "sub": "geography"
  }
]

This is the query I have to group by session type.
    db.collection.aggregate([
  {
    $group: {
      _id: "$type",
      groupedData: {
        $push: {
          key: "$key",
          "sub": "$sub",
          "type": "$type"
        }
      }
    }
  }
])

By this I get 
    [
  {
    "_id": "classroom",
    "groupedData": [
      {
        "key": 3,
        "sub": "english",
        "type": "classroom"
      },
      {
        "key": 5,
        "sub": "english",
        "type": "classroom"
      },
      {
        "key": 5,
        "sub": "geography",
        "type": "classroom"
      }
    ]
  },
  {
    "_id": "studio",
    "groupedData": [
      {
        "key": 1,
        "sub": "english",
        "type": "studio"
      },
      {
        "key": 2,
        "sub": "history",
        "type": "studio"
      },
      {
        "key": 4,
        "sub": "english",
        "type": "studio"
      }
    ]
  }
]

But I want the count of a subject in studio and class room and total count of sessions in studio and classroom 
Eg. 
{
  studio: { count: 3, englishInStudio: 2, historyInStudio: 1 },
  classroom: {count: 3, englishInClassroom: 2, geographyInClassroom: 1}
}


You can do this by specifying a document as your key to group on
db.test.aggregate([
  { $group: {
    _id: { "type": "$type", "sub" : "$sub"},
     count: { $sum: 1}
   }
}]);

This will output the following, which get your required values but it's in a different format:
{ "_id" : { "type" : "classroom", "sub" : "english" }, "count" : 2 }
{ "_id" : { "type" : "studio", "sub" : "history" }, "count" : 1 }
{ "_id" : { "type" : "classroom", "sub" : "geography" }, "count" : 1 }
{ "_id" : { "type" : "studio", "sub" : "english" }, "count" : 2 }

