Skip to content

Instantly share code, notes, and snippets.

@zchking
Forked from clarkenheim/mongodb_distinct_count.js
Last active August 5, 2020 02:50
Show Gist options
  • Save zchking/adcbe6c8a3ce43aa57842fba34305f9a to your computer and use it in GitHub Desktop.
Save zchking/adcbe6c8a3ce43aa57842fba34305f9a 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}}]);
db.order.aggregate([{ $group: { _id: "$seller_email", total_order: { "$sum": 1 },
seller_address_1 : { $first: '$seller_address_1' },
seller_country : { $first: '$seller_country' },
seller_id : { $first: '$seller_id' },
seller_phone : { $first: '$seller_phone' },
seller_city : { $first: '$seller_city' },
seller_email : { $first: '$seller_email' },
seller_name : { $first: '$seller_name' },
seller_postcode : { $first: '$seller_postcode' }}},
{ $out: "seller_info" }
],
{ allowDiskUse: true})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment