MongoDB – Aggregation:

Aggregation is the processing of data records and return the compiled results. It groups the data from multiple documents to return a single result.

syntax: db.collection_name.aggregate(aggregate_operation)

Example: Let us first query the existing collection name “students”

Let‘s aggregate the data which shows the number of students from each city.
db.students.aggregate([{$group:{_id:”$city”, students:{$sum:1}}}])

Other Functions in MongoDB :

Expression Description
$sum Summates the defined values from all the documents in a collection
$avg Calculates the average values from all the documents in a collection
$min Return the minimum of all values of documents in a collection
$max Return the maximum of all values of documents in a collection
$addToSet Inserts values to an array but no duplicates in the resulting document
$push Inserts values to an array in the resulting document
$first Returns the first document from the source document
$last Returns the last document from the source document