The Aggregation Pipeline
A report is data on a conveyor belt: each stage does one job and hands its documents to the next. Filter with $match, total and average with $group, and shape, sort and trim the result.
Updated
Pipeline Basics
- The Aggregation Pipeline: Data on a Conveyor Belt (Apprentice): An aggregation pipeline sends a collection's documents through a list of stages, each doing one job, so the database can answer report questions that find can't, starting with $match to choose the documents and $count to count them.
- $group: Totals, Counts and Averages (Journeyman): The $group stage sorts documents into groups by the value of a field, or puts them all in one group, and computes each group's total, count, average, smallest, biggest and first value with accumulators.
- Shaping the Report: $project, $set, $sort and $limit (Journeyman): Four stages turn a pipeline's correct answer into a report someone can read, $sort and $limit for the top few, $project to choose and rename fields, and $set to compute new ones with expressions such as $multiply and $round, and the order of the stages changes what comes out.
Exercise: Sales by Category
- Exercise: Sales by Category (Journeyman): Write five aggregation pipelines for Riverbend Bike Shop's sales dashboard, from the revenue of each category to the three biggest orders, and let the tests run each one on a year of orders and check its rows.