Counting and summing
$group$sum
Counting and summing are the two things you will do with $group more than everything else combined. They are the same operator: $sum: 1 counts, $sum: "$field" totals.
Now let’s count orders per user.
{
$group: {
_id: "$userId",
orderCount: {
$sum: 1
}
}
}
Result:
[
{
_id: 101,
orderCount: 2
},
{
_id: 102,
orderCount: 1
}
]
Mental translation:
Group by userId
For every document:
add 1
This is very similar to:
GROUP BY userId
COUNT(*)
Sum a field
Suppose documents:
{
userId: 101,
amount: 500
}
{
userId: 101,
amount: 300
}
Pipeline:
{
$group: {
_id: "$userId",
totalSpent: {
$sum: "$amount"
}
}
}
Result:
{
_id: 101,
totalSpent: 800
}
Try it
db.orders.aggregate([
{
$group: {
_id: "$userId",
orderCount: { $sum: 1 }
}
},
{ $sort: { orderCount: -1 } },
{ $limit: 5 }
])
The busiest five users. Change $sum: 1 to $sum: "$rating" and the same pipeline totals a field instead of counting documents.