Skip to content

Instantly share code, notes, and snippets.

View tejpratap46's full-sized avatar
🏠
Working from home

Tej Pratap Singh tejpratap46

🏠
Working from home
View GitHub Profile
@tejpratap46
tejpratap46 / mongodb_distinct_count.js
Created May 25, 2016 09:06 — forked from clarkenheim/mongodb_distinct_count.js
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}}]);