I have a MongoDB aggregation operation that uses a couple of groups:
{ $group: { "_id": { "vid": "$visitor_id", "pid":"$project.id" } } }
{ $group: { "_id": "$_id.vid", "count": { $sum: 1} } }
that returns the following data:
{
"results": [
{
"_id": "user1",
"count": 1
},
{
"_id": "user2",
"count": 2
},
{
"_id": "user3",
"count": 1
}
]
}
How could I go about returning the total number of users with more than 1 project (count
field). In this case it would be something like:
{
total: 1
}
because only user2
has more than 1 project (count
> 1).
I've tried adding the following group operation to no avail:
{
$group: {
"_id": null,
count: {
$sum: {$cond: [{$gt: ['$_id.count', 1]}, 1, 0]}
}
}
}
Any ideas?
You can achieve your desired result as simple as adding the following three aggregation stages into your pipeline:
{$match: {count: {$gt: 1}}}
{$group: {_id: null, total: {$sum: 1}}}
{$project: {_id: 0, total: 1}}
$match
stage to filter all the users that have more than 1 projects.$group
stage to count the total number of such users.total
field.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With