
Question:
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?
Answer1:As already pointed out by <a href="https://stackoverflow.com/users/1259510/johnnyhk" rel="nofollow">JohnnyHK</a>, use <a href="https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#db-collection-distinct" rel="nofollow">db.collection.distinct</a> if possible as it provides the chance of <a href="https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#index-use" rel="nofollow">leveraging indexes</a>
So in your case db.collection.distinct('category').length
should be pretty fast.<br />
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.