Aggregation Pipeline: $match, $group, $project, $sort, $lookup
Explore how to build and optimize MongoDB aggregation pipelines using key stages such as $match to filter, $group to summarize, $project to reshape, $sort to order, and $lookup to join collections. This lesson helps you understand how to transform and analyze data beyond basic queries for practical MERN stack applications.
find() retrieves documents, but it does not summarize them inside the database. Questions like “What is the total revenue per category?” or “How many orders does each user have?” require grouping documents, calculating values, and reshaping the result, which is the role of the aggregation pipeline. An aggregation pipeline is an ordered list of stages. Each stage receives the documents from the previous stage, transforms them, and passes the result to the next stage, like an assembly line for data. This lesson covers five core stages: $match, $project, $group, $sort, and $lookup.
Note: The examples are runnable mongo shell aggregations against the seeded
ecommercecollections. Eachaggregate([...])call lists its stages in the order they run.
To make the pipeline concrete, the next visual should show documents flowing through the five stages in sequence:
That starts with the stage that narrows the input. ... ...