Last active
December 12, 2023 09:22
-
-
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)
This file contains 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 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}}]); |
Tnx for sharing this! I'm just wondering how fast does it work on large datasets? Could you please share any numbers regarding performance?
Thanks!
Thanks!
you legend!
thank you
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saved my life. Thanks!