Aggregation Framework
The aggregation framework allows you to process data records and return computed results. It is similar to theGROUP BY clause in SQL but much more powerful.
The Pipeline
Aggregations work as a pipeline. Documents pass through a series of stages, where each stage transforms the documents.Common Stages
$match
Filters the documents (like find or SQL WHERE).
$group
Groups documents by a specified identifier key and applies the accumulator expression(s) to each group.
$project
Reshapes each document in the stream, such as by adding new fields or removing existing fields.
$sort
Sorts all input documents and returns them to the pipeline in sorted order.
$limit & $skip
Used for pagination.
Example Pipeline
Calculate the total sales per product for the year 2023, sorted by highest sales.Summary
- Aggregation Pipeline processes data in stages.
- Use
$matchto filter early (for performance). - Use
$groupto calculate statistics (sum, avg, etc.). - Use
$projectto format the output.