Reputation: 7145
I have a collection called users
and that has a property called orders
. orders is an array if present sometimes orders might not exist in the document.
I want to take all the orders count. I did this aggregation query.
[
{
$match: {
orders: { $exists: true },
},
},
{
$project: {
ordersCount: {
$size: '$orders',
},
},
},
]
This returns each user's orders count separately. But I want to take the sum
of it.(Total orders count)
How do I achieve this with MongoDB?
Upvotes: 0
Views: 51
Reputation: 17858
If you want to get all the sum of orders you can use the following aggregation:
[
{
$match: {
orders: {
$exists: true
}
}
},
{
$group: {
_id: null,
totalCount: {
$sum: {
$size: "$orders"
}
}
}
}
]
Upvotes: 1