-2

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?

rl99
  • 501
  • 2
  • 5
  • 13

1 Answers1

2

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}}])

fgakk
  • 1,289
  • 1
  • 15
  • 26