Title: Mongodb, aggregate nr of items in $group
Tags: mongodb;mongodb-query;aggregation-framework
Question: I'm doing some aggregation to get some statistics on a how many products there are in cateories.

After some piping I'm down to this:

```[
  {
     topCategory: "Computer",
     mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Laptop"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },
```

]

Wanted output:

```[
  {
    name: "Computer",
    count: 4,
    mainCategories: [
      {
         name: "Laptop",
         count: 2
      },
      {
         name: "Stationary",
         count: 2
      }
    ]
  }
]
```

My query so far:

```let query = mongoose.model('Product').aggregate([
    {
      $match:  {
        project:  mongoose.Types.ObjectId(req.params.projectId)
      }
    },
    { $project:  {
        _id: 0,
        topCategory: '$category.top',
        mainCategory: '$category.main',
      }
    },
 ]);
```

I know I need to use ```$group``` combined with ```$sum```. I tried different way's but can't get it work.

Comment: use  group  `{
   $group : { 
    _id : "$topCategory",
    "count" :  { $sum : 1 },
                                mainCategories: { $push:  { name: "$mainCategory"} }
    }
   }
  }`

Here is the accepted answer: In this case first you should group by ```mainCategory``` and then group by ```topCategory``` as below 

```db.collection.aggregate({
  $group: {
    _id: "$mainCategory",
    "count": {
      $sum: 1
    },
    "data": {
      "$push": "$$ROOT"
    }
  }
}, {
  "$unwind": "$data"
}, {
  "$group": {
    "_id": "$data.topCategory",
    "count": {
      "$sum": 1
    },
    "mainCategories": {
      "$addToSet": {
    "name": "$_id",
    "count": "$count"
      }
    }
  }
}).pretty()
```



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:01/14/17', 'FavoriteCount': 0.0, 'PostTypeId': 1, 'Tags': '<mongodb><mongodb-query><aggregation-framework>', 'Title': 'Mongodb, aggregate nr of items in $group', 'ViewCount': 56, 'id': 41649807, 'user_AboutMe': '', 'user_AccountId': 1715321.0, 'user_DisplayName': 'Joe', 'user_Reputation': 5418.0, 'user_Views': 792.0, 'user_id': 1572526.0}}