Introduction
Aggregation helps combine and summarize data so you can see important information quickly on dashboards.
db.collection.aggregate([
{ stage1 },
{ stage2 },
...
])db.sales.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])db.users.aggregate([
{ $group: { _id: "$country", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])db.orders.aggregate([
{ $match: { status: "shipped" } },
{ $group: { _id: "$customerId", totalSpent: { $sum: "$price" } } },
{ $sort: { totalSpent: -1 } }
])$group stage in a MongoDB aggregation pipeline for reporting dashboards?$group stage collects documents into groups and calculates summary statistics like sums or averages.$match filters, $sort orders, and $addFields adds fields, but only $group aggregates data.aggregate() with an array of stages.db.collection.aggregate([{ $match: { status: 'active' } }]) is valid; others use wrong methods or syntax.sales with documents like { product: 'A', quantity: 5 } and { product: 'B', quantity: 3 }, what will this aggregation return?db.sales.aggregate([
{ $group: { _id: '$product', totalQuantity: { $sum: '$quantity' } } },
{ $sort: { totalQuantity: -1 } }
])$group stage groups documents by product and sums their quantities: 'A' -> 5, 'B' -> 3.$sort orders results by totalQuantity descending, so 'A' (5) comes before 'B' (3).db.orders.aggregate([
{ $match: { status: 'completed' } },
{ $group: { _id: '$customerId', total: { $sum: '$amount' } } },
{ $sort: { total: 1 } },
{ $project: { customerId: 1, total: 1 } }
])_id: '$customerId', the output fields are _id and total. The original customerId field is renamed to _id.customerId, which does not exist; it should use _id instead.$group to get average order amount and count of orders per customer.$match after grouping to keep only customers where count > 3.Pass the test and this pattern moves unknown