Mongo count occurrences of each value for a set of documents

ritmatter picture ritmatter · Jan 18, 2015 · Viewed 37.5k times · Source

I have some documents like this:

{
  "user": '1'
},
{ "user": '1'
},
{
  "user": '2'
},
{
  "user": '3'
}

I'd like to be able to get a set of all the different users and their respective counts, sorted in decreasing order. So my output would be something like this:

{
  '1': 2,
  '2': 1,
  '3': 1
}

I think this can be done with a Mongo aggregate(), but I'm having a lot of trouble figuring out the right flow for this.

Answer

Disposer picture Disposer · Jan 18, 2015

You can get result (not in your required format) via aggregation

db.collection.aggregate(
   {$group : { _id : '$user', count : {$sum : 1}}}
).result

the output for your sample documents is:

"0" : {
    "_id" : "2",
    "count" : 1
},
"1" : {
    "_id" : "3",
    "count" : 1
},
"2" : {
    "_id" : "1",
    "count" : 2
}