MongoDB Aggregation
Aggregation is the process toward combining things. That is, assembling those things so we can refer to them altogether. Data aggregation is often used to give statistical analysis for groups of information and to create useful summary data for business analysis. Aggregation is done on a large scale for a major software application.
When MongoDB users need to accumulate metrics from a MongoDB database, aggregation of MongoDB is the best tool for this. In MongoDB, the Aggregation process returns an average of all values seen during the group and project. It gathers values from different documents and groups them together and then performs various kinds of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.
MongoDB provides three ways to perform aggregation -
- Aggregation pipeline
- Map-reduce function
- Single-purpose aggregation
MongoDB aggregate() Method
MongoDB provides aggregate() method to perform the aggregation.
Syntax of aggregate() Method
db.collection_name.aggregate(aggregate_operation)
It returns the collective average of all numeric values that result from applying a specified expression to each document in a group of documents. It is available in the group and project stages.
MongoDB Aggregate Example
Suppose we have a collection named product, we want to get the average product amount and average quantity.
db.product.insert([
{'item': 'iron', 'price': 120, 'quantity': 2},
{'item':'alloy', 'price':90, 'quantity': 1},
{'item':'steel', 'price':47, 'quantity': 3},
{'item':'alloy', 'price':70, 'quantity': 6},
{'item':'iron', 'price':56, 'quantity':4}
]);
The following statement returns the average product amount and average quantity.
db.product.aggregate(
[{
"$group" : {
"_id": "$item",
avgAmt: { $avg: {$multiply: ["$price", "$quantity"]}},
avgQty: { $avg: "$quantity"}
}
}]
)

In the above example, we have grouped documents by the field item.
Different Aggregation Expressions
These are the following a list of available aggregation expressions.
Expression |
Description |
---|---|
$sum | Adds up the defined value from all documents in the collection. |
$avg | Calculates the average of all given values from every document in the collection. |
$min | Gets the minimum of all values from within a collection. |
$max | Gets the maximum of all values from within a collection. |
$push | Inserts the value to an array in the associated document. |
$first | Gets the first document from the source documents according to the grouping. |
$last | Gets the last document from the source documents according to the grouping. |