Lesson 3.2:
Aggregation Mastery
The Database as a Processor
Performance in distributed systems is often limited by network overhead. The Aggregation Framework allows you to perform complex data transformations inside the database, sending only the final result to Node.js.
Pipeline Optimization
Modern MongoDB v8.0+ optimizes pipelines automatically. However, placing $match and $limit as early as possible remains the golden rule for indexing efficiency.
// Example: Monthly Revenue Report
const sales = await collection.aggregate([
{ $match: { status: "shipped" } },
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$orderDate" } },
revenue: { $sum: "$total" }
}
},
{ $sort: { _id: -1 } }
]).toArray();
Window Operators & Facets
Use $setWindowFields for running totals and $facet to return multiple report views (e.g., categories + totals) in a single database round-trip.
Check Your Knowledge
Which stage should generally be placed first in an aggregation pipeline?