MongoDB tutorials
6. Aggregation and group by clause – MongoDB tutorials
Video tutorial:
Aggregation means grouping multiple documents and perform some calculations based on any specific field. So, for example, you have a list of users having name and age and you want to know the number of users in each age, then the command for that will be:
db.users.aggregate({ $group: { "_id": "$age", "total_users": { $sum: 1 } } })
We are using the aggregate function and it has an $group operator which is an object. In this you can tell all the columns that need to be returned, by setting “_id”: “$age” we are telling that the _id field will have the value of age, and “total_users” is further an object which has an operator $sum. This will add all the documents based on the same age and return those records. Example of output:
{ "_id": 29, "total_users": 2 }
{ "_id": 30, "total_users": 1 }
{ "_id": 31, "total_users": 0 }
It says that there are 2 people having age 29, and 1 user having age 30 and none (0) having age 31.