Aggregation for MongoDBs
The MongoDB aggregation pipeline processes documents through ordered stages such as $match, $group, $project, $sort, $lookup and $unwind, each feeding the next. It is used for reports, joins and analytics inside the database. This unit sits in the Performance stage and builds on indexes and good modelling.
Stage: Performance · Part of the MongoDB roadmap · Last reviewed 19 November 2026
What to learn in Aggregation
- Build a pipeline that filters with $match and groups with $group
- Compute totals and averages using accumulators such as $sum and $avg
- Join two collections with $lookup and flatten results with $unwind
- Place $match and $sort early so the pipeline can use indexes
- Reshape output fields with $project and $addFields
Aggregation interview questions
Why should $match come early in an aggregation pipeline?
An early $match reduces the number of documents flowing into later stages, and when it is at the start it can use an index. Filtering first saves memory and time, while a late $match makes expensive stages process data that is thrown away.
What does $lookup do in MongoDB?
$lookup performs a left outer join with another collection, matching a local field to a foreign field and adding the matches as an array. It is useful for reports, but heavy use in hot paths suggests the data model should embed instead.
Where Aggregation fits in the MongoDB roadmap
Aggregation belongs to the Performance stage (intermediate level), which takes about 12 hours. Indexes and aggregation.
Other units in this stage
Back to the full MongoDB roadmap