Quick revision
The short answer
The pipeline is $match on status 'COMPLETED' and createdAt between 2026-01-01 and 2027-01-01 first, so an index can be used, then $group by customerId summing total and counting orders, then $sort by spent descending and $limit 5. MongoDB combines the adjacent $sort and $limit so it keeps only the current top five in memory. Money should be stored as Decimal128 so the sums have no floating-point errors, and if we need customer names we add a $lookup after the $limit, so only five lookups run.
What to remember
In this answer, we built a top-five pipeline by putting $match first, so an index on status and createdAt reduces the input, then $group to sum totals and count orders per customer, then $sort and $limit, which MongoDB merges into a bounded top-n sort. We used a half-open date range, stored money as Decimal128 so sums are exact, joined customer names only after the limit, and wrote the same pipeline with Spring Data MongoDB.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The pipeline is $match on status 'COMPLETED' and createdAt between 2026-01-01 and 2027-01-01 first, so an index can be used, then $group by customerId summing total and counting orders, then $sort by spent descending and $limit 5. MongoDB combines the adjacent $sort and $limit so it keeps only the current top five in memory. Money should be stored as Decimal128 so the sums have no floating-point errors, and if we need customer names we add a $lookup after the $limit, so only five lookups run.
Why this question is asked
Top-N reports such as 'best customers this year' are among the most common aggregation pipelines in real applications, and they are a good interview exercise because the correct answer depends on stage order. The same five stages in a different order can be ten times slower or return wrong money totals. In this answer, we will recap what an aggregation pipeline is, write the pipeline stage by stage with the reason for each position, see the floating-point problem and its fix, add customer names efficiently, and finally write the same thing in Java with Spring Data MongoDB.
1A Quick Recap of the Aggregation Pipeline
An aggregation pipeline is a list of stages. Documents from the collection flow into the first stage, its output flows into the next, and so on. $match filters, $group combines documents that share a key and computes accumulators like $sum, $sort orders, $limit keeps the first n, and $lookup joins another collection.
Order matters for two reasons. First, only stages at the start of the pipeline that read directly from the collection, like a leading $match or $sort, can use an index. Second, every stage processes whatever the previous one produced, so filtering early means every later stage has less work.
2Writing the Pipeline Step by Step
Here is the full pipeline in mongosh, with what each stage leaves behind.
- orders collection10,000,000 documents
- $match COMPLETED in 20261,200,000 left, read through the index
- $group by customerId85,000 customer totals
- $sort spent desc + $limit 5keeps only the top 5 while sorting
- $lookup customer names5 lookups
5 steps in order. Play them, or step through them one at a time.
Each stage shrinks the data; the expensive join runs on 5 documents.
Notice the date range: greater than or equal to the first of January 2026 and strictly less than the first of January 2027. Using $lt on the next year's start is safer than $lte on 31 December, which would miss orders placed later on that day.
The $match comes first so it can use an index. With an index on {status: 1, createdAt: 1}, MongoDB reads only the 2026 completed orders instead of the whole collection; status is an equality condition and createdAt a range, so this order follows the equality, sort, range guideline. The $group then turns perhaps a million orders into one document per customer, with the total spent and an order count; $sum: 1 adds one per document, which is how we count.
3Why $sort Then $limit Is Cheap
Sorting 85,000 group results sounds expensive, but MongoDB's optimizer notices a $sort immediately followed by a $limit and merges them. Instead of sorting everything and then cutting, it keeps a small running list of the best five documents seen so far and discards the rest as they arrive. Memory use is proportional to the limit, not to the input, so the sort never comes near the per-stage memory limit.
The $group itself is a blocking stage: it must see every matching order before it can emit any total. For one year of orders and tens of thousands of customers, that easily fits within its memory limit. For much larger cases, allowDiskUse lets it spill to disk, and a pre-computed summary collection is better still.
4Money Needs Decimal128
If total is stored as a normal double, the sums can be slightly wrong, because binary floating point cannot represent most decimal fractions exactly.
Over millions of orders those tiny errors add up and a report no longer matches the accounting system. Decimal128 is MongoDB's exact decimal type, and $sum over Decimal128 values stays exact. In Java, a BigDecimal field in an entity maps to Decimal128 when the mapping is configured for it; by default Spring Data MongoDB has historically stored BigDecimal as a string, so check your version and set the field's target type to Decimal128 explicitly.
5Adding Customer Names After the Limit
The report probably needs names, which live in the customers collection. The key is to join after the limit.
If $lookup came before $group, it would run once for each of 1.2 million orders. After $limit it runs exactly five times, each an indexed lookup by _id.
6The Same Pipeline in Spring Data MongoDB
In a Spring Boot service the pipeline is built with the Aggregation API, and the result is mapped to a small record.
The structure is the same as in mongosh, so the same reasoning about stage order applies. Spring maps the group's _id to the record's id field.
7Follow-up questions
Why not sort in the application?
Because we would have to transfer all 85,000 customer totals to the application to keep five. The database can compute the top five with a small bounded memory footprint and send back five documents.
What if two customers tie for fifth place?
The result is not deterministic. If ties matter, add a tie-breaker to the sort, such as {spent: -1, _id: 1}, so the output is stable across runs.
How would you make this report fast for a dashboard that reloads every minute?
Pre-aggregate: a scheduled pipeline that ends with $merge writes per-customer yearly totals into a summary collection, and the dashboard reads the top five from that collection with a simple sorted query on an index.
8Conclusion
In this answer, we built a top-five pipeline by putting $match first, so an index on status and createdAt reduces the input, then $group to sum totals and count orders per customer, then $sort and $limit, which MongoDB merges into a bounded top-n sort. We used a half-open date range, stored money as Decimal128 so sums are exact, joined customer names only after the limit, and wrote the same pipeline with Spring Data MongoDB.
Open with
I would write four stages. First a match on status COMPLETED and createdAt greater than or equal to the first of January 2026 and less than the first of January 2027.
Then, if they want more
Putting the match first matters because only a leading match can use an index, ideally on status and createdAt, and it shrinks the input for everything after it. Using less than the next year's start avoids missing orders late on New Year's Eve.
Second, a group with underscore id set to customerId, spent as the sum of total, and orders as a sum of one, which counts the orders. Third, a sort on spent descending, and fourth a limit of five.
MongoDB merges a sort followed directly by a limit, so it only keeps the current top five in memory instead of sorting every customer. Two practical points. Money should be stored as Decimal128, because summing doubles gives errors like 0.30000000000000004 and the report would drift from accounting.
And if the report needs customer names, I add the lookup into customers after the limit, so it runs five times instead of once per order. In Spring Data this is the same pipeline built with Aggregation.match, group, sort and limit, mapped to a small record.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- MongoDB manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write an aggregation pipeline over orders {customerId, status, total, createdAt} that...": https://scrivio-interview-library.netlify.app/databases/mongodb/50fea027fb/