Skip to content

Instantly share code, notes, and snippets.

@clarkenheim
Last active December 12, 2023 09:22
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save clarkenheim/fa0f9e5400412b6a0f9d to your computer and use it in GitHub Desktop.
Save clarkenheim/fa0f9e5400412b6a0f9d 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 cnt, fieldName FROM someTable GROUP BY fieldName;
db.someCollection.aggregate([{"$group" : {_id:"$fieldName", cnt:{$sum:1}}}]);
//as above but ordered by the count descending
//eg: SELECT COUNT(*) AS cnt, fieldName FROM someTable GROUP BY fieldName ORDER BY cnt DESC;
db.someCollection.aggregate([{"$group" : {_id:"$fieldName", cnt:{$sum:1}}}, {$sort:{'cnt':-1}}]);
@jpesquibel
Copy link

Saved my life. Thanks!

@alsma
Copy link

alsma commented Jan 23, 2018

Tnx for sharing this! I'm just wondering how fast does it work on large datasets? Could you please share any numbers regarding performance?

@a-lapkov
Copy link

Thanks!

@sachith95
Copy link

Thanks!

@NoobieDog
Copy link

you legend!

@doomedraven
Copy link

thank you

@LloydThinks
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment