Question 22 / 50
ImportantMediumScenarioAggregation
Product wants the top 3 customers by completed-order spend. How would you write the pipeline, and what index would you want?
Think about it first.
Short answer
$match completed orders, $group by userId summing amount, $sort by total descending, $limit 3. An index on { status: 1 } — or { status: 1, userId: 1, amount: 1 } if you can cover — lets $match use IXSCAN before the grouping work.
Why?
$sort plus $limit can be a top-k sort, which is cheaper than sorting every group. Do not $lookup the user until after the limit unless you need the name in the same round trip — and even then, looking up three users is cheap.
Example
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } },
{ $limit: 3 }
])How did you do?