Introduction to Aggregation Pipelines
🎯 Introduction
We have learned to retrieve and filter documents with find. Applications also need answers to questions such as “How many users live in each city?” and “What is the average age in each city?” These grouped statistics require more than find alone.
In this final article, you will understand MongoDB's aggregation pipeline, combine the common $match, $group, and $sort stages, and learn when to use find or a pipeline.
🧱 What Is an Aggregation Pipeline?
An aggregation pipeline chains processing steps together. Data passes through each stage in order; each stage processes its input and passes the result to the next.
Think of a factory assembly line: raw materials (collection documents) enter at one end, pass through filtering, grouping, and sorting, and emerge as finished products (statistical results).
The basic syntax is db.collectionName.aggregate(), with an array of stages in execution order:
db.user.aggregate([
{ stage1 },
{ stage2 },
]);
The array order determines the data flow: stages listed first execute first.
Before starting, connect to mongosh and prepare the sample data. We will include multiple users in each city where possible so the statistics are meaningful:
docker exec -it mongo-demo mongosh -u root -p 123456 --authenticationDatabase admin
use blog_demo
// Clear existing data so the results match this article
db.user.deleteMany({})
db.user.insertMany([
{ username: 'Xiao Ming', age: 20, city: 'Beijing' },
{ username: 'Xiao Hong', age: 25, city: 'Shanghai' },
{ username: 'Xiao Gang', age: 30, city: 'Guangzhou' },
{ username: 'Xiao Li', age: 28, city: 'Beijing' },
{ username: 'Zhou Qi', age: 26, city: 'Beijing' },
{ username: 'Wu Ba', age: 24, city: 'Shanghai' },
]);
mongo:8). deleteMany({}) empties the collection. Skip it if you have data you want to keep, but your statistics may differ from the examples.✨ $match and $group
There are many aggregation stages. Start with two common ones: $match and $group.
$match filters documents, excluding those that do not meet its conditions. Its filter syntax is the same as find. For example, select users in Beijing:
db.user.aggregate([
{ $match: { city: 'Beijing' } },
]);
Like db.user.find({ city: 'Beijing' }), this returns Xiao Ming, Xiao Li, and Zhou Qi. Why use a pipeline? Because $match is usually one step before further processing.
$group calculates grouped statistics, a central aggregation capability. For example, count users by city:
db.user.aggregate([
{
$group: {
_id: '$city',
count: { $sum: 1 },
},
},
]);
The result is:
[
{ _id: 'Beijing', count: 3 },
{ _id: 'Shanghai', count: 2 },
{ _id: 'Guangzhou', count: 1 },
]
There are three important details:
_id: '$city': In$group,_idspecifies the group key, rather than the original document ID. Documents with the same city value belong to the same group.'$city': In an aggregation expression, prefix a field name with$to reference its value. Without$, MongoDB treats it as a literal string.count: { $sum: 1 }: Creates acountfield and adds one for every document in the group. You choose this output field name;totalwould work too.
Imagine sorting playing cards into piles by suit: _id determines the grouping rule, and $sum: 1 counts the cards in each pile.
⚡ Combining Stages
Each stage handles one part of the task. The power comes from combining stages. Let's select users aged 24 or older, group them by city, calculate counts and average ages, then sort by count from highest to lowest.
db.user.aggregate([
// Stage 1: Select documents with age >= 24
{ $match: { age: { $gte: 24 } } },
// Stage 2: Group by city and calculate counts and average ages
{
$group: {
_id: '$city',
count: { $sum: 1 },
avgAge: { $avg: '$age' },
},
},
// Stage 3: Sort by count in descending order
{ $sort: { count: -1 } },
]);
Follow the data through the pipeline:
$matchexcludes Xiao Ming, age 20, leaving Xiao Hong, Xiao Gang, Xiao Li, Zhou Qi, and Wu Ba: five documents.$groupcreates three groups: Beijing has two users (Xiao Li, 28, and Zhou Qi, 26), Shanghai has two (Xiao Hong, 25, and Wu Ba, 24), and Guangzhou has one (Xiao Gang, 30).$avg: '$age'calculates each group's average age.$sortusescount: -1for descending count order (1means ascending), putting cities with more users first.
The result is:
[
{ _id: 'Beijing', count: 2, avgAge: 27 },
{ _id: 'Shanghai', count: 2, avgAge: 24.5 },
{ _id: 'Guangzhou', count: 1, avgAge: 30 },
]
$sort comes before $group, it sorts the original documents, where count does not yet exist, so that sort is not meaningful. When building a pipeline, consider the shape of the data entering each stage.💡 Choosing Between find and aggregate
Why not use find for everything? Use these guidelines:
- Retrieving documents: Use
findfor filtering, sorting, and pagination. Its syntax is straightforward. - Grouping, statistics, or multiple processing steps: Use
aggregate, for example to count users by city, calculate averages, or filter, group, and sort results.findalone cannot directly perform these grouped calculations.
Think of find as retrieving data and aggregate as analyzing it. You will use find more often, while pipelines are especially useful for reports and statistics.
❓ Questions and Answers
Q1: Why does $group return a city name in _id instead of a document ID?
In $group, _id defines the group key. With _id: '$city', each output _id is the city value for that group. This is part of $group syntax and is separate from the original documents' _id fields.
Q2: When do field names need a $ prefix?
In aggregation expressions, use $ to access a field's value, as in '$city' or '$age'. A string without it is literal text. $match filters use the same syntax as find, so their field keys do not need the prefix.
Q3: Does aggregate modify the collection?
The pipelines shown here only read documents and return processed results. The original documents stay unchanged, so you can run these pipelines repeatedly.
Q4: Why use $match if its filter is the same as find?
For filtering alone, they serve the same purpose. $match is useful because it combines with $group and $sort, reducing the input before statistics are calculated so later stages process fewer documents.
Q5: What other statistical operators are useful besides $sum and $avg?
Common options include $max for the largest field value in a group, $min for the smallest, and $first for a field value from the first document in a group. Once you understand $sum and $avg, these follow a similar pattern.
🧪 Exercises
Exercise 1: Group users by city and calculate the maximum age in each city. Hint: use $max.
db.user.aggregate([
// Write your code here
]);
Exercise 2: Select users aged 25 or older, count them by city, and sort the counts in ascending order.
db.user.aggregate([
// Write your code here
]);
🎉 You have learned aggregation pipeline basics and completed the MongoDB course! You started with Docker installation and CRUD operations, then explored query filters, nested documents and arrays, the official Node.js driver, and Mongoose. Finally, you used indexes to improve queries and pipelines to calculate grouped statistics. Together with the Express and Node.js courses, these skills give you the database foundation to build a full-stack project. Pick a small project and put them into practice!
