Aggregation processes documents through a pipeline of stages. Each stage receives documents, transforms them, and passes results to the next stage — like Unix pipes for your data.
Top 5 customers by spend
db.orders.aggregate([
{ $match: { status: "delivered" } }, // filter first
{ $group: {
_id: "$userId",
totalSpent: { $sum: "$total" },
orders: { $sum: 1 }
}},
{ $sort: { totalSpent: -1 } },
{ $limit: 5 }
])$match and $sort
$match uses the same syntax as find(). Put it first whenever possible so later stages process fewer documents (and so it can use indexes).
$group and accumulators
$group collects documents by the _id expression and computes accumulators: $sum, $avg, $min, $max, $push, $addToSet, $first, $last. Use { $sum: 1 } to count.
mongosh
db.products.aggregate([
{ $group: {
_id: "$category",
avgPrice: { $avg: "$price" },
count: { $sum: 1 }
}}
])Field references
Strings starting with $ reference fields: "$price" means *the value of the price field*. _id: null groups everything into one bucket.