Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tejpratap46/478b1e9469d5d56250ea57b8802b547c to your computer and use it in GitHub Desktop.
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)
//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