Question 18 / 50
ImportantMediumConceptAggregation
How does $group work, and what does _id mean inside it?
Think about it first.
Short answer
_id is the grouping key — the expression whose distinct values define the buckets. Every other field is an accumulator over the documents in that bucket. _id: null groups the whole stream into one bucket.
Why?
The key can be a composite object, such as { city: '$city', year: { $year: '$createdAt' } }. $group does not preserve order, so you $sort afterwards if you need a ranking. Accumulators like $sum, $avg, $push are the 'SELECT aggregations' of MongoDB.
Example
db.orders.aggregate([
{
$group: {
_id: "$status",
count: { $sum: 1 },
revenue: { $sum: "$amount" }
}
}
])Interview tip
If asked for 'per user per month', put an object in _id rather than grouping twice.
Common mistake
Forgetting that $group wipes fields you did not accumulate. You cannot $sort by createdAt after $group unless you kept it.
How did you do?