backendBy Zahid Khan
What is Aggregation in MongoDB?
Aggregation is used to process and transform data and return computed results (like sum, count, average, grouping).
Why We Use Aggregation:
We use aggregation when we need:
Grouping data
Calculations (sum, avg, count)
Filtering large datasets
Data transformation
Analytics / reports
Example use cases:
Total sales per customer
Average salary per department
Count users by city
//orders
{
"customer": "Zahid",
"amount": 100
}
{
"customer": "Ali",
"amount": 200
}
{
"customer": "Zahid",
"amount": 300
}
db.orders.aggregate([
{
$group: {
_id: "$customer",
totalAmount: { $sum: "$amount" }
}
}
]);
//output
[
{ "_id": "Zahid", "totalAmount": 400 },
{ "_id": "Ali", "totalAmount": 200 }
]
#mongo