Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ackuser/fb7531c7cf1a4da833aaba69d82718d0 to your computer and use it in GitHub Desktop.
Save ackuser/fb7531c7cf1a4da833aaba69d82718d0 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