I have some documents like this: Show
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:
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. asked Jan 18, 2015 at 18:36
3 You can get result (not in your required format) via aggregation
the output for your sample documents is:
answered Jan 18, 2015 at 18:47
DisposerDisposer 6,1014 gold badges29 silver badges38 bronze badges 3 For anyone reading this in Jan
2019 the accepted answer does not currently work in Robo3T (returns a You must: a) wrap the query in a set of square brackets b) remove 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.
answered Jan 16, 2019 at 15:52
Ruben MurrayRuben Murray 1,07710 silver badges16 bronze badges With MongoDb 3.6 and newer, you can leverage the use of
which yields
answered Sep 9, 2019 at 15:17
chridamchridam 97.1k21 gold badges223 silver badges227 bronze badges You can use the below aggregation query, It will also sort the results in decreasing order as desired.
answered Jul 15, 2020 at 15:10
2 Docs Home → MongoDB Manual $count Passes a document to the next stage that contains a count of the number of documents input to the stage. Note
The
where TipSee also:A collection named
The following aggregation operation has two stages:
The operation returns the following results: How do I count documents in MongoDB?7 Ways to Count Documents in MongoDB. The count command.. The db. collection. count() method.. The db. collection. countDocuments() method.. The db. collection. estimatedDocumentCount() method.. The cursor. count() method.. The $count aggregation pipeline operator.. The $sortByCount aggregation pipeline operator.. How do I count documents in a collection?var value = db. collection. count(); and then print(value) or simply value , would give you the count of documents in the collection named collection .
Where is count field in MongoDB?In the Map step iterate over the properties of each document as a javascript object, output the count and reduce to get the total. Show activity on this post. For a simple way just find() all value and for each set of record get size of array. then for each set of result, get the size of array.
How do I count distinct values in MongoDB?How does distinct count works. By using the above-mentioned syntax, the distinct fields are retrieved by using the distinct() method whereas the “. length” will count the number of fields returned by the distinct() method. There are a few MongoDB-based Ubuntu instances that must be ready to get to the practice session.
|