Aggregate
- Node.js course
- Advanced
- Lesson 29/83
- 5 min
Learn the Mongoose aggregate pipeline.
What is Aggregate?
Aggregate is MongoDB's pipeline-based data processing tool. It passes documents through stages to group, filter, sort, and compute. This enables complex analytics that simple queries cannot do.
The pipeline is an array of stages. Each stage takes documents, processes them, and passes them to the next. For example [{ $match: { age: { $gt: 18 } } }, { $group: { _id: "$city", count: { $sum: 1 } } }] first filters adults, then groups by city. You run it with Model.aggregate(pipeline).
Aggregate stages
Each pipeline stage starts with an operator. $match filters documents (like find). $group groups documents by a key and computes ($sum, $avg). $sort sorts. $count gives the document count.
Stages run in array order; the order matters. Filtering with $match first reduces the document count, so later stages run faster. This is critical for performance on large datasets.
Practice Log the type of aggregate
Import mongoose. Create a model with mongoose.model("User", { name: String }). Log typeof User.aggregate.
Starter code
// import the module
// create a model
// log the type of aggregateSample solution
const mongoose = require("mongoose");
const User = mongoose.model("User", { name: String });
console.log(typeof User.aggregate);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the method name
const results = await User.____([{ $match: {} }])
const results = await User.aggregate([{ $match: {} }])
Explanation: User.aggregate([...]) runs the pipeline.
2 Match each piece to its role
| Term | Meaning |
|---|---|
$match |
Filters |
$group |
Groups |
$sort |
Sorts |
$count |
Counts |
3 What parameter does aggregate take?
- An array of stages Correct answer
- Bir dize
- A number
- Bir fonksiyon
Explanation: aggregate takes an array of stages.