What is aggregation in MongoDB?
Aggregation in MongoDB is a mechanism for processing and transforming data within a collection to produce a final result: statistics, grouping, filtering, sorting, counts, and so on. It works through a pipeline, a sequence of stages, where each stage transforms or selects data before passing it on.
What this looks like
An example pipeline:
js
db.sales.aggregate([
{ $match: { status: "A" } }, // filtering
{ $group: { _id: "$item", total: { $sum: "$price" } } } // grouping and totaling
])What you can do with aggregation
filter, selecting only the documents you need ($match)group, grouping and computing sums, averages, and so on ($group)sort, sorting ($sort)project, picking/changing fields ($project)limit/skip, restricting the result set
When it's used
- statistics (sums, averages, max/min)
- reports
- complex queries instead of several separate ones
- preparing data for analytics
Summary
Aggregation is a powerful MongoDB tool for analytics and data processing through a pipeline of stages, letting you filter, group, and compute final values in a single query.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.