Let's break it down simply
In an aggregation pipeline, documents pass through each stage in order. Putting $match early trims the data down before $group does its counting and grouping. aggregate() doesn't touch the underlying collection data unless $out or $merge is used.
javascript
db.orders.aggregate([
{ $match: { status: 'paid' } },
{
$group: {
_id: '$customerId',
orderCount: { $sum: 1 },
totalSpent: { $sum: '$total' }
}
},
{ $match: { totalSpent: { $gte: 100000 } } },
{ $sort: { totalSpent: -1 } },
{ $project: { _id: 0, customerId: '$_id', orderCount: 1, totalSpent: 1 } }
])You should see
{ customerId: 42, orderCount: 3, totalSpent: 185000 }Try it yourself
Group the products collection by category and calculate the average price and product count.
Aggregation Pipeline — MongoDB