Introduction
In MongoDB, the order of steps in a pipeline changes the final result. Each step works on the output of the previous one, so the sequence is important.
In MongoDB, the order of steps in a pipeline changes the final result. Each step works on the output of the previous one, so the sequence is important.
[
{ stage1 },
{ stage2 },
...
]Each stage is an object inside an array.
Stages run one after another in the order they appear.
[
{ $match: { status: "active" } },
{ $sort: { age: 1 } }
][
{ $sort: { age: 1 } },
{ $match: { status: "active" } }
]This query finds users with status 'active' first, then sorts them by age from youngest to oldest.
db.users.aggregate([
{ $match: { status: "active" } },
{ $sort: { age: 1 } }
])Changing the order of stages can change the result or make the query slower.
Always filter early to reduce data size for later stages.
Pipeline stages run in the order you write them.
Order affects both results and performance.
Filter early, then sort or group for best results.
db.orders.aggregate([
{ $sort: { price: -1 } },
{ $match: { status: 'A' } }
])db.sales.aggregate([
{ $group: { _id: "$item", total: { $sum: "$amount" } } },
{ $match: { $gt: ["$total", 100] } }
])Pass the test and this pattern moves unknown