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
}
For anyone reading this in Jan 2019 the accepted answer does not currently work in Robo3T (returns a pipeline.length - 1
error).
You must:
a) wrap the query in a set of square brackets []
b) remove .result
from the end
https://github.com/Studio3T/robomongo/issues/1519#issuecomment-441348191
Here's an update to the accepted answer by @disposer that works for me in Robo3T.
db.getCollection('collectionName').aggregate(
[ {$group : { _id : '$user', count : {$sum : 1}}} ]
)