Created
November 12, 2015 16:39
-
-
Save matthieuprat/1fbac7cbab37eb65f7c8 to your computer and use it in GitHub Desktop.
Mongo's distinct with occurrences
This file contains hidden or 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
| /** | |
| * 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