Pipeline Basics & Stages
Pipeline Basics & Stages
Section titled “Pipeline Basics & Stages”An aggregation pipeline is an ordered array of stages.
db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$userId", totalSpent: { $sum: "$totalAmount" } } }, { $sort: { totalSpent: -1 } }])orders collection -> $match filter completed orders -> $group group by user -> $sort highest spenders first -> resultStage Rules
Section titled “Stage Rules”- Stages run from top to bottom.
- Each stage outputs documents for the next stage.
- Stage order matters for correctness and performance.
- Put filtering stages early when possible.
- Use
$projectto remove large fields if later stages do not need them.
Aggregation vs find()
Section titled “Aggregation vs find()”Use find() for simple reads:
db.users.find({ role: "admin" })Use aggregate() when you need transformation:
db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$userId", total: { $sum: "$totalAmount" } } }])Common Pipeline Patterns
Section titled “Common Pipeline Patterns”Filtering:
[{ $match: { status: "active" } }]Report:
[ { $match: { status: "completed" } }, { $group: { _id: "$category", revenue: { $sum: "$amount" } } }, { $sort: { revenue: -1 } }]Join and reshape:
[ { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }, { $unwind: "$user" }, { $project: { totalAmount: 1, "user.name": 1 } }]