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”

 testset:PRIMARY>db.students.find()
{ "_id" : ObjectId("59245acd5273c93ad95b109b"), "firstname" : "Maria", "city" : "Dallas", "age" : 21, "fee" : 1500 }
{ "_id" : ObjectId("59246d4b5273c93ad95b109c"), "firstname" : "sneha", "city" : "Delhi", "age" : 21, "fee" : 1000 }
{ "_id" : ObjectId("59246d7b5273c93ad95b109d"), "firstname" : "jay", "city" : "toronto", "age" : 21, "fee" : 1000 }
{ "_id" : ObjectId("59254ec6c2c4480ef9a1e5bb"), "firstname" : "harry", "city" : "Dallas", "age" : 24, "fee" : 2500 }
{ "_id" : ObjectId("59254f0cc2c4480ef9a1e5bc"), "firstname" : "rita", "city" : "LasVegas", "age" : 22, "fee" : 5000 }
{ "_id" : ObjectId("59254f2dc2c4480ef9a1e5bd"), "firstname" : "prasad", "city" : "newyork", "age" : 26, "fee" : 3500 }
{ "_id" : ObjectId("59254f47c2c4480ef9a1e5be"), "firstname" : "devi", "city" : "LasVegas", "age" : 26, "fee" : 1000 }

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

testset:PRIMARY>db.students.aggregate([{$group:{_id:"$city", students:{$sum:1}}}])
{ "_id" : "newyork", "students" : 1 }
{ "_id" : "LasVegas", "students" : 2 }
{ "_id" : "toronto", "students" : 1 }
{ "_id" : "Delhi", "students" : 1 }
{ "_id" : "Dallas", "students" : 2 }

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