Forked from matthieuprat/mongo-distinct-with-count.js
Created
November 13, 2018 04:14
-
-
Save thelebster/7b0496256eb1b14859e5f9f569759db9 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