MongoDB Aggregation
MongoDB’s aggregation framework processes data through a pipeline of stages to perform complex transformations, filtering, grouping, and computations. Below is a concise overview of aggregation with examples using the MongoDB Node.js driver, assuming a users collection with documents like { name: “Alice”, age: 25, city: “New York”, salary: 50000 }.
Aggregation Pipeline
A pipeline consists of stages, each transforming the input documents and passing the result to the next stage. Common stages include $match, $group, $sort, $project, $unwind, and $lookup.
- Performance: Use $match early to reduce documents. Indexes improve efficiency.
- Accumulators: $sum, $avg, $push, $addToSet, etc., work in $group.
- Syntax: Each stage is an object in an array. Pipelines execute sequentially.
- Output: Use .toArray() to get results or iterate with cursors for large datasets.
- Debugging: Test pipelines stage-by-stage to verify intermediate outputs.
Get Sivaraksi’s stories in your inbox
Join Medium for free to get updates from this writer.




