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?
db.collection.distinct('category').lengthas an alternative?distinctcan use an index but$groupcannot.