Aggregation in MongoDB is a powerful feature used to process and transform data from a collection. It works like SQL’s GROUP BY and allows data to be analyzed and reshaped efficiently using a pipeline of stages.
db.collection.aggregate([
{ stage1 },
{ stage2 },
...
])
db.orders.aggregate([
{ $group: { _id: "$userId", totalOrders: { $sum: 1 } } }
])
$match → Filters documents (like WHERE in SQL)$group → Groups documents by a field$project → Reshapes the documents (selects fields)$sort → Sorts the result set$limit → Limits number of documents$count → Counts documents
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } }
])
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!