MongoDB Aggregation is an operation used to process data and return computed results. Using Aggregation, we can perform Count, Sum, Average and Match.

There are three ways to perform aggregation, aggregation pipeline, map-reduce pipeline and single purpose aggregation methods.

Sample Database


[{"name": "swift","type": "hatchback","price":"800000"},
 {"name": "ciaz","type": "sedan","price":"1000000"},
 {"name": "baleno","type": "hatchback","price":"850000"},
 {"name": "baleno rs","type": "hatchback","price":"950000"},
 {"name": "scross","type": "crossover","price":"11500000"},
 {"name": "brezza","type": "suv","price":"990000"},
 {"name": "gypsy","type": "suv","price":"750000"}
]    
{ "_id" : "gypsy" }
{ "_id" : "baleno rs" }
{ "_id" : "ciaz" }
{ "_id" : "baleno" }
{ "_id" : "swift" }
{ "_id" : "brezza" }
{ "_id" : "scross" }
db.suzuki.aggregate([{$group:{ _id:'$name' }}])

This Aggregation operation will assign value of name in id.

{ "_id" : "sedan" }
{ "_id" : "hatchback" }
{ "_id" : "crossover" }
{ "_id" : "suv" }
db.suzuki.aggregate([{$group:{ _id:'$type' }}])

This Aggregation operation will check total type of cars.


$sum

To check sum to defined values from collection.

{ "_id" : "suv", "total" : 2 }
{ "_id" : "crossover", "total" : 1 }
{ "_id" : "sedan", "total" : 1 }
{ "_id" : "hatchback", "total" : 3 }
db.samp.aggregate([{$group:{ _id:'$type', total:{$sum:1} }}])

This Aggregation operation will check total type of cars in collections.

{ "_id" : "crossover", "total" : 11500000 }
{ "_id" : "suv", "total" : 1740000 }
{ "_id" : "sedan", "total" : 1000000 }
{ "_id" : "hatchback", "total" : 2600000 }
db.samp.aggregate([{$group:{ _id:'$type', total:{$sum:'$price'} }}])

This Aggregation operation will check total price of all car types in collection.



$avg

$sum operator is used to check average in collections.

{ "_id" : "suv", "total" : 870000 }
{ "_id" : "crossover", "total" : 11500000 }
{ "_id" : "sedan", "total" : 1000000 }
{ "_id" : "hatchback", "total" : 866666.6666666666 }
db.samp.aggregate([{$group:{ _id:'$type', total:{$avg:'$price'} }}])

$min

$min operator is used to check minimum value in collections.

{ "_id" : "sedan", "total" : 1000000 }
{ "_id" : "hatchback", "total" : 800000 }
{ "_id" : "suv", "total" : 750000 }
{ "_id" : "crossover", "total" : 11500000 }
db.samp.aggregate([{$group:{ _id:'$type', total:{$min:'$price'} }}])

$max

$max operator is used to check maximum value in collections.

{ "_id" : "hatchback", "total" : 950000 }
{ "_id" : "crossover", "total" : 11500000 }
{ "_id" : "sedan", "total" : 1000000 }
{ "_id" : "suv", "total" : 990000 }
db.samp.aggregate([{$group:{ _id:'$type', total:{$max:'$price'} }}])