Mongo count occurrences of each value for a set of documents

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
}

Leave a Comment