Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of groups that meet a certain condition with MongoDB aggregate framework?

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?

like image 354
ashe540 Avatar asked Oct 19 '22 14:10

ashe540


1 Answers

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}}
  1. As chridam mentined you can have a $match stage to filter all the users that have more than 1 projects.
  2. Then use another $group stage to count the total number of such users.
  3. The third step is just cosmetics, leaves only the total field.
like image 179
bagrat Avatar answered Nov 01 '22 08:11

bagrat