What is Aggregation in MongoDB?
Learn what MongoDB aggregation is, how the pipeline of $match, $group, $lookup, and other stages works together, with a practical worked example.
Expected Interview Answer
Aggregation in MongoDB is the process of transforming and computing over documents through a pipeline of stages, such as filtering, grouping, and reshaping, to produce summarized or restructured results.
The aggregation pipeline passes documents through an ordered sequence of stages like `$match` to filter, `$group` to summarize by key, `$sort`, `$project` to reshape fields, and `$lookup` to join data from another collection. Each stage consumes the output of the previous one, similar to piping commands together, which lets you build complex analytics such as totals per category or joined reports without pulling raw data into application code. MongoDB executes many stages efficiently inside the database engine, and indexes can accelerate early stages like `$match` or `$sort`. Aggregation replaces older approaches like map-reduce for most analytical workloads.
- Chains stages like $match, $group, $sort, $project, $lookup
- Performs filtering and computation inside the database
- Enables joins across collections with $lookup
- Faster and more maintainable than client-side aggregation
- Index-aware for stages like $match and $sort early in the pipeline
AI Mentor Explanation
Aggregation is like a scorer running raw ball-by-ball data through a series of stations: filter to one innings, group by bowler, then sum wickets taken. Each station passes its output to the next, the way a MongoDB aggregation pipeline chains stages such as $match and $group to turn raw documents into a summary report.
Step-by-Step Explanation
Step 1
Pipeline of stages
Documents flow through an ordered list of stages, each transforming the output of the stage before it.
Step 2
Filtering with $match
$match narrows the working set early, ideally using an indexed field to reduce documents fast.
Step 3
Grouping with $group
$group buckets documents by a key and computes accumulators like $sum, $avg, or $push.
Step 4
Reshaping with $project
$project selects, renames, or computes fields to shape the final output document.
Step 5
Joining with $lookup
$lookup performs a left outer join against another collection, pulling in related documents.
What Interviewer Expects
- Explains aggregation as a pipeline of ordered stages
- Names common stages: $match, $group, $sort, $project, $lookup
- Understands stage output feeds directly into the next stage
- Knows $match early in a pipeline can use indexes
- Can contrast aggregation with simple find() queries
Common Mistakes
- Filtering with $match only at the end instead of as early as possible
- Forgetting $group requires an _id key to bucket documents by
- Assuming aggregation always requires pulling data into application code
- Confusing the aggregation pipeline with the deprecated map-reduce approach
Best Answer (HR Friendly)
“Aggregation is how MongoDB summarizes and reshapes data, like calculating totals or generating reports directly inside the database instead of pulling all the raw data out first. It works like an assembly line, where each step refines the data a bit more before passing it to the next step.”
Code Example
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$category", totalRevenue: { $sum: "$amount" }, count: { $sum: 1 } } },
{ $sort: { totalRevenue: -1 } },
{ $project: { category: "$_id", totalRevenue: 1, count: 1, _id: 0 } }
]);
// => [{ category: "electronics", totalRevenue: 48250, count: 312 }, ...]Follow-up Questions
- What is the difference between $match and a plain find() query?
- How does $lookup perform a join between two collections?
- What accumulator operators can you use inside $group?
- How can you optimize an aggregation pipeline for performance?
- What is the difference between the aggregation framework and map-reduce?
MCQ Practice
1. What is the aggregation pipeline made of?
The aggregation pipeline processes documents through an ordered sequence of stages, each transforming the previous output.
2. Which stage is used to join data from another collection?
$lookup performs a left outer join against another collection within the pipeline.
3. Why should $match usually appear early in a pipeline?
Placing $match early filters out documents as soon as possible and can take advantage of existing indexes.
Flash Cards
What is MongoDB aggregation? — A pipeline of stages that transforms and computes over documents to produce summarized results.
Name three common aggregation stages. — $match, $group, and $lookup (also $sort and $project).
Which stage joins two collections? — $lookup, performing a left outer join.
Why place $match early in a pipeline? — To reduce the working set quickly and take advantage of indexes.