1. Understanding the Aggregation Framework
Why aggregation is useful
A find() query retrieves documents that match a condition. Real applications often need to calculate totals, group records, combine collections, transform arrays, and create reports. MongoDB's aggregation framework processes documents through an ordered sequence of stages.
A pipeline can filter source documents, reshape them, calculate values, group them, enrich them with related data, and return the final result. A stage's output becomes the next stage's input.
Use find() for straightforward retrieval. Use aggregation when the answer must be computed or transformed across documents. Aggregation is not automatically faster; performance depends on the pipeline, indexes, data volume, and workload.
- Input:
Documents from a collection or another supported source - Processing:
An ordered sequence of aggregation stages - Output:
Transformed documents, calculated results, or written output
A pipeline does not necessarily return one document per input document. $match can reduce the count, $unwind can increase it, and $group can reduce many documents to a few summaries.
db.orders.aggregate([
{ $match: { status: "delivered" } },
{ $sort: { createdAt: -1, _id: -1 } }
]);- Aggregation processes documents through ordered stages.
- Stages can filter, reshape, group, expand, enrich, and write data.
- Aggregation is useful for reporting and analytics.
What is the primary purpose of MongoDB's aggregation framework?