Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo count occurrences of each value for a set of documents

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.

like image 401
ritmatter Avatar asked Jan 18 '15 18:01

ritmatter


People also ask

How do I count the number of documents in MongoDB?

Description. n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB connection. n = count( conn , collection ,'Query', mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.

Can we use count with aggregate function in MongoDB?

MongoDB aggregate $count element in array For this, MongoDB provides the $size aggregation to count and returns the total number of items in an array. Let's get understand this with the help of an example. Example: The subsequent documents were inserted into the Test collection.

How do I count multiple fields in MongoDB?

In MongoDB, when we have a large dataset inside the collection and we want to count where the field value is repeating on multiple fields then we use $group aggregation. Example: Here, we are taking an example in which we apply $group aggregation with multiple fields and get the count of duplicate field values.


2 Answers

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 } 
like image 88
2 revs, 2 users 67% Avatar answered Sep 28 '22 09:09

2 revs, 2 users 67%


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}}} ] ) 
like image 42
Reece Daniels Avatar answered Sep 28 '22 09:09

Reece Daniels