How to count the number of groups satisfying a certain condition with the aggregate structure of MongoDB?

I have a MongoDB aggregation operation that uses multiple groups:

{ $group: { "_id": { "vid": "$visitor_id", "pid":"$project.id" } } }
{ $group: { "_id": "$_id.vid", "count": { $sum: 1} } }

which returns the following data:

{
  "results": [
    {
      "_id": "user1",
      "count": 1
    }, 
    {
      "_id": "user2",
      "count": 2
    },
    {
      "_id": "user3",
      "count": 1
    }
  ]
}

How can I return to the total number of users with more than 1 project (field count). In this case, it will be something like this:

{
  total: 1
}

because it only user2has more than 1 project ( count> 1).

I tried to add the following group operation to no avail:

{ 
  $group: { 
    "_id": null, 
    count: {
      $sum: {$cond: [{$gt: ['$_id.count', 1]}, 1, 0]}
    } 
  } 
}

Any ideas?

+4
source share
1 answer

, :

{$match: {count: {$gt: 1}}}
{$group: {_id: null, total: {$sum: 1}}}
{$project: {_id: 0, total: 1}}
+3

All Articles