Skip to content

Instantly share code, notes, and snippets.

@clarkenheim
clarkenheim / mongodb_distinct_count.js
Last active Apr 20, 2021
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)
View mongodb_distinct_count.js
//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}}]);
@clarkenheim
clarkenheim / 99bottles.js
Created Jan 3, 2013
The song "99 bottles of beer" in 2 lines of javascript
View 99bottles.js
var i=99,w=" on the wall",t=" bottle",o=" of beer";
for(;i;)b=i+(i^1?t+'s':t)+o,console.log(b+w+", "+b+".\nTake one down and pass it around, "+--i+(i^1?t+'s':t)+w)