Count Distinct Values via aggregation framework
January 14, 2015 Leave a comment
Q: Is it possible to count distinct values of a field in mongodb?
A: Yes! This can be done via the aggregation framework in mongo. This takes two group commands; the first groups by all the distinct values, and the second does a count of them all.
pipeline = [ { $group: { _id: "$myNonUniqueFieldId"} }, { $group: { _id: 1, count: { $sum: 1 } } } ]; db.runCommand( { "aggregate": "collection" , "pipeline": pipeline } );