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.
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.
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.
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.
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}}} ] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With