Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate distinct count on fields in mongodb

I have following collection:

[{
    "id": 1,
    "activity_type": "view",
    "user_id": 1
},
{
    "id": 2,
    "activity_type": "save",
    "user_id": 1
},
{
    "id": 3,
    "activity_type": "save",
    "user_id": 1
},
{
    "id": 4,
    "activity_type": "save",
    "user_id": 2
}]

I need to get a result like this:

[{
   "activity_type": "view",
   "count": 1,
   "user_count": 1
},{
   "activity_type": "save",
   "count": 3,
   "user_count": 2
}]

So far I reached on this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

db.getCollection('activities').aggregate([
{
    $group:{_id:"$activity_type", count: {$sum: 1}}
},    
{
    $project: 
    {
        _id: 0,
        activity_type: "$_id",
        count: 1
    }
}
])

It gives me:

[{
    "activity_type": "view",
    "count": 1
},
{
    "activity_type": "save",
    "count": 3
}]

How can I add distinct user_id count as well?

>Solution :

What you need to do is use $addToSet in the group stage to gather the unique ids, after that in the $project stage you can use $size to show the proper user count.

db.collection.aggregate([
  {
    $group: {
      _id: "$activity_type",
      count: {
        $sum: 1
      },
      user_ids: {
        "$addToSet": "$user_id"
      }
    }
  },
  {
    $project: {
      _id: 0,
      activity_type: "$_id",
      user_count: {
        $size: "$user_ids"
      },
      count: 1
    }
  }
])

Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading