Signup/Sign In

Aggregation in MongoDB

Aggregation in MongoDB is nothing but an operation used to process the data that returns the computed results. Aggregation basically groups the data from multiple documents and operates in many ways on those grouped data in order to return one combined result. In sql count(*) and with group by is an equivalent of MongoDB aggregation.

Aggregate function groups the records in a collection, and can be used to provide total number(sum), average, minimum, maximum etc out of the group selected.

In order to perform the aggregate function in MongoDB, aggregate () is the function to be used. Following is the syntax for aggregation :

db.collection_name.aggregate(aggregate_operation)

Let us now see how to make use of the aggregate function in MongoDB. Consider a collection named books with the data as shown below :

NOTE : Create a collection named books, with fieldnames - title, price and type. Use db.books.find() to list down the contents of the collection.

Aggregation in MongoDB


Now, from the above collection, let us use the aggregate function to group the books which are of the type ebook and online. Following command will be used :

db.books.aggregate([{$group : {_id: "$type", category: {$sum : 1}}}])

Group Aggregation in MongoDB

The above aggregate function will give result, which says there are 2 records of the type ebook and 2 records of the type online. So the above aggregation command, has grouped our collection data, based on their type.


Different expressions used by Aggregate function

ExpressionDescription
$sumSummates the defined values from all the documents in a collection
$avgCalculates the average values from all the documents in a collection
$minReturn the minimum of all values of documents in a collection
$maxReturn the maximum of all values of documents in a collection
$addToSetInserts values to an array but no duplicates in the resulting document
$pushInserts values to an array in the resulting document
$firstReturns the first document from the source document
$lastReturns the last document from the source document