Skip to content

Instantly share code, notes, and snippets.

@matthieuprat
Created November 12, 2015 16:39
Show Gist options
  • Select an option

  • Save matthieuprat/1fbac7cbab37eb65f7c8 to your computer and use it in GitHub Desktop.

Select an option

Save matthieuprat/1fbac7cbab37eb65f7c8 to your computer and use it in GitHub Desktop.
Mongo's distinct with occurrences
/**
* Like Mongo's db.collection.distinct but with counts for each field value.
* See https://docs.mongodb.org/v3.0/reference/method/db.collection.distinct.
*
* Example:
* > distinct('inventory', 'items.sku', { dept: 'A' })
* { "111" : 2, "333" : 1 }
*/
function distinct(collection, field, query) {
var map = {}
db[collection].aggregate([
{ $match: query || {} },
{ $group: { _id: '$' + field, c: { $sum: 1 } } },
{ $sort: { _id: -1 } },
]).forEach(function (g) {
map[g._id] = g.c
})
return map
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment