An assembly line for data
Reports need grouping, totals and reshaping. The aggregation pipeline passes documents through stages, each transforming the output of the last: filter → group → sort → reshape. It's MongoDB's answer to SQL's GROUP BY and much more.
Stages
printjson(db.dishes.aggregate([
{ $match: { price: { $gte: 100 } } },
{ $group: { _id: "$category", dishes: { $sum: 1 }, avgPrice: { $avg: "$price" }, names: { $push: "$name" } } },
{ $sort: { avgPrice: -1 } },
{ $project: { _id: 0, category: "$_id", dishes: 1, avgPrice: { $round: ["$avgPrice", 0] }, names: 1 } },
]));- { $sum: 1 } counts documents; { $sum: "$price" } adds a field.
- _id: null groups everything into one result.
- $count, $limit, $skip, $addFields and $sortByCount are handy shortcuts.