Aggregation Pipeline Operators — MongoDB Technical Interview Questions & Answers
$match, $group, $project, $sort and $lookup.
Aggregation Pipeline Operators
- Simple meaning: Aggregation is a pipeline: documents go through stages. Each stage’s output is the next stage’s input.
- How to use: db.students.aggregate([ { $match: { city: "Pune" } }, { $group: { _id: "$city", avg: { $avg: "$marks" } } }, { $sort: { avg: -1 } } ]).
- Common stages: $match (filter), $group (totals), $project (shape), $sort, $limit, $lookup (join-like).
- Try this: average marks per city. Put $match first so you group less data.
- Common mistake: $group without _id. Using find() when you needed a total.
- Interview tip: “$match → $group → $sort. Like WHERE then GROUP BY.”
Technical Interview Tip: One pipeline: filter, group, sort. Say why $match is first.
Code Examples for Aggregation Pipeline Operators
Aggregation Pipeline Operators — working example
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$city", total: { $sum: "$amount" }, count: { $sum: 1 } } },
{ $project: { _id: 0, city: "$_id", total: 1, count: 1 } },
{ $sort: { total: -1 } }
])Aggregation Pipeline Operators — aggregation pipelines transform documents stage by stage ($match → $group → $project → $sort).
How to Explain Aggregation Pipeline Operators to an Interviewer
Name three aggregation stages.
$match $group $sort (or $project / $lookup)