-
-
Save tejpratap46/478b1e9469d5d56250ea57b8802b547c to your computer and use it in GitHub Desktop.
MongoDB equivalent of an SQL query to get the distinct values of a field in a collection including the count of documents which have each distinct value (distinct with count)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//equivalent of MySQL "SELECT COUNT(*) AS `count`, `fieldName` FROM `someTable` GROUP BY `fieldName | |
db.someCollection.aggregate([{"$group" : {_id:"$fieldName", count:{$sum:1}}}]); | |
//as above but ordered by the count descending | |
db.someCollection.aggregate([{"$group" : {_id:"$fieldName", count:{$sum:1}}}, {$sort:{'count':-1}}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment