While .distinct() works well for getting individual values ββfor a field, in order to actually get the number of occurrences, this is better for the aggregation structure :
Collection.aggregate([ { "$group": { "_id": "$field", "count": { "$sum": 1 } }} ],function(err,result) { });
The .distinct() method also performs an "abstract", from which the specified "excellent" field is actually located inside the array. In this case, you first need to call $unwind to process the elements of the array here:
Collection.aggregate([ { "$unwind": "$array" }, { "$group": { "_id": "$array.field", "count": { "$sum": 1 } }} ],function(err,result) { });
So, the main work is mainly done in $group by grouping field values, which means the same as "excellent". $sum is a grouping operator, which in this case simply adds 1 for each occurrence of this value in the field for this collection.
source share