What is the aggregation $group stage and its accumulator operators?
Why Interviewers Ask This
This tests whether you can apply MongoDB knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
The $group stage groups input documents by a specified identifier expression and applies accumulator operators to compute aggregated values for each group. It's MongoDB's equivalent of SQL's GROUP BY. Syntax: { $group: { _id: groupByExpression, field1: { accumulatorOp: expression }, ... } }. The _id specifies the group key; set _id to null to aggregate over all documents. Accumulator operators: $sum: sum of numeric values ({ $sum: "$price" }) or count with { $sum: 1 }; $avg: arithmetic mean; $min / $max: minimum/maximum value; $first / $last: first/last value in the group (depends on sort order); $push: creates an array of all values in the group; $addToSet: like $push but with unique values only; $count: count of documents (MongoDB 5.0+); $stdDevPop / $stdDevSamp: standard deviation; $mergeObjects: merges documents into one; $accumulator: custom accumulator with JavaScript (flexible but slow). Multi-field grouping: _id: { year: "$year", month: "$month" } — group by multiple fields. $group + $sort + $limit = Top-N per group: group → push all into array → $slice to take first N. Or use $topN/$bottomN (MongoDB 5.2+): { $topN: { n: 3, sortBy: { score: -1 }, output: "$name" } }.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last MongoDB project, I used this when...' immediately makes your answer more credible and memorable.
Previous
What is the difference between $unwind and $lookup in MongoDB?
Next
How does MongoDB handle geospatial data?