Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count distinct values in mongoDB

Tags:

mongodb

This is the document structure in mongoDB

{ "_id" :ObjectId("9elesdf3lk3jppefll34d210"), "category" :"data1",product:'data'}
{ "_id" :ObjectId("9elesdf3lk3jppefll34d211"), "category" : "data2",product:'data'}
{ "_id" :ObjectId("9elesdf3lk3jppefll34d211"), "category" : "data1",product:'data' }

where category is indexed. I want to take a distinct count of the category field.

Currently I am using the following code to take the counts

db.collection.aggregate( 
   {$group : {_id : "$category"} }, 
   {$group: {_id:1, count: {$sum : 1 }}})

This query was giving me proper counts but my database is increasing day by day and the query is taking longer to execute. Is there some other methodology to take the counts in a faster way?

like image 725
mikhil mohanan Avatar asked Oct 16 '25 16:10

mikhil mohanan


1 Answers

As already pointed out by JohnnyHK, use db.collection.distinct if possible as it provides the chance of leveraging indexes

So in your case db.collection.distinct('category').length should be pretty fast.
If you still suffer from performance issues then have a look at

db.collection.explain().distinct('category')  

to see the execution plan of the query and take actions on it or provide it to this question so that we see whether your index is actually used.

like image 179
DAXaholic Avatar answered Oct 18 '25 10:10

DAXaholic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!