Core trio: filter rows, aggregate metrics, shape output fields.
Group with accumulators
db.orders.aggregate([
{ $match: { status: { $in: ['shipped', 'delivered'] } } },
{ $group: {
_id: { year: { $year: '$shippedAt' }, customerId: '$customerId' },
orders: { $sum: 1 },
revenue: { $sum: '$total' }
}},
{ $project: { customerId: '$_id.customerId', year: '$_id.year', orders: 1, revenue: 1, _id: 0 } }
])Practice: Run aggregation pipelines in mongosh.
Accumulators
$sum, $avg, $max, $push, $addToSet—pick by report needs.
Important interview questions and answers
- Q: $push vs $addToSet?
A: $push keeps duplicates; $addToSet unique values per group. - Q: $project after $group?
A: Flattens nested _id for API-friendly JSON.
Self-check
- What does $sum: '$total' do?
- Difference $push vs $addToSet?
Tip: $addToSet when you need unique values per group; $push keeps duplicates.
Interview prep
- $group _id?
- Grouping key; null groups all docs.
- $project role?
- Shapes output fields after group.