100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
MongoDB

Common Aggregation Stages

A practical tour of the most frequently used aggregation stages — $match, $project, $sort, $limit, $skip, and $unwind — and how they reshape documents.

AggregationIntermediate10 min readJul 10, 2026
Analogies

Filtering with $match

$match filters documents using the same query syntax as find(), and it is the workhorse stage for narrowing the working set before heavier operations run. When $match appears as the first stage in a pipeline, MongoDB can use an existing index to satisfy it exactly as it would for a normal query, which is why the query planner's explain() output shows an IXSCAN for a well-indexed leading $match. A $match placed later in the pipeline, after a $project or $group has already reshaped documents, cannot use collection indexes because it is now operating on transformed, in-memory documents rather than the original collection.

🏏

Cricket analogy: Selecting only the overs bowled by pacers before analyzing economy rates narrows the dataset to exactly what matters, just as $match narrows documents to those meeting a condition before further processing.

Reshaping with $project

$project controls which fields appear in the output documents and can compute new fields using expressions. You can include fields with a value of 1, exclude them with 0, rename them, or derive entirely new computed fields such as concatenating strings or performing arithmetic on existing values. A common pattern is projecting only the fields a downstream stage or the client actually needs, which reduces the size of documents flowing through the rest of the pipeline and reduces the payload sent back over the network.

🏏

Cricket analogy: A scorecard app that shows only runs, balls faced, and strike rate instead of every raw delivery-by-delivery event mirrors $project trimming a document down to relevant fields.

Ordering and Pagination: $sort, $skip, and $limit

$sort orders documents by one or more fields, $limit caps the number of documents that pass through, and $skip discards a specified number of leading documents, commonly used together for pagination. Order matters here too: a $sort placed before $limit produces a true top-N result, whereas $limit before $sort would arbitrarily cap documents before they've been ordered, giving an unpredictable and usually wrong result. For large offsets, $skip becomes increasingly expensive because MongoDB must still walk through and discard every skipped document, so range-based pagination using a $match on an indexed cursor field is often preferred over deep $skip values.

🏏

Cricket analogy: Requesting the top five run-scorers for a tournament only makes sense if you sort the batting list before cutting it to five, just as $sort must precede $limit to get a correct top-N result.

javascript
db.products.aggregate([
  { $match: { category: "electronics" } },
  { $project: { name: 1, price: 1, discountedPrice: { $multiply: ["$price", 0.9] } } },
  { $sort: { discountedPrice: -1 } },
  { $skip: 20 },
  { $limit: 10 }
]);

Using a large $skip value for pagination on big collections causes MongoDB to scan and discard every skipped document on each request, so page 500 of a $skip-based paginated list can be dramatically slower than page 1. Prefer cursor-based pagination with an indexed field for deep pagination.

Flattening Arrays with $unwind

$unwind deconstructs an array field from each input document, outputting one document per array element while copying all other fields unchanged. It's essential when you need to treat array elements as individual rows for grouping or filtering, for example computing per-tag statistics from an array of tags on blog posts. By default, documents where the array field is missing, null, or an empty array are dropped from the output entirely, unless you set preserveNullAndEmptyArrays: true, a detail that surprises many developers when documents mysteriously vanish from pipeline results.

🏏

Cricket analogy: Breaking a match's list of all sixes hit into individual events so each six can be attributed to a batter mirrors $unwind exploding an array field into separate documents.

$unwind pairs naturally with $group: unwind an array to get one document per element, then group by that element to compute per-item aggregates, such as counting how many orders contained each product.

  • $match filters documents using find()-style query syntax and can use indexes only when it is the first stage in the pipeline.
  • $project shapes output documents by including, excluding, renaming, or computing fields.
  • $sort orders documents and must precede $limit to produce a correct top-N result.
  • $skip and $limit together implement pagination, but deep $skip values are expensive on large collections.
  • $unwind expands an array field into one document per element, dropping documents with missing or empty arrays unless preserveNullAndEmptyArrays is set.
  • $unwind is commonly paired with $group to compute per-element aggregates from array data.
  • Reducing document size early with $project or $match lowers memory and network overhead for the rest of the pipeline.

Practice what you learned

Was this page helpful?

Topics covered

#MongoDB#MongoDBStudyNotes#Database#CommonAggregationStages#Common#Aggregation#Stages#Filtering#StudyNotes#SkillVeris