Question

I have collection where each document has user related details. userid:1001,abc:1 userid:1001,abc:9 userid:1002,abc:1 userid:1001,abc:3

Something like this. I wanted to get count of userId which has maximum occurances. I need to do this on Mongo shell.

Any ideas?

Was it helpful?

Solution

Check the aggregation framework of mongo. For the answer you can use $group operator to group by userid and sorting them based count. Something like this:

Suppose collection name is test:

db.test.aggregate([{"$group":{"_id":"$userid","occurence":{"$sum":1}}},{$sort:{"occurence":-1}}])

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top