Aggregation pipeline — match, group, project, unwind
Answer out loud or in your head first, then compare.
Answer
A pipeline processes a stream of documents in stages. Match filters, group aggregates, project shapes the results, and unwind splits an array into separate documents.
JavaScript
db.orders.aggregate([
{ $match: { status: 'paid' } },
{ $group: { _id: '$customerId', total: { $sum: '$amount' } } },
{ $sort: { total: -1, _id: 1 } },
{ $limit: 5 }
]);To be precise: sorting by the total comes after the group; a limit before grouping would change what the result means. In the example, amount is the value of the whole order.
Pitfall: unwind can multiply documents and inflate a sum. Filtering early helps, but every stage still has to match the task's logic.
How did it go? Be honest — “Not yet” puts the question on your review list.