mongodb count num of distinct values per field/key

前端 未结 6 1975
小蘑菇
小蘑菇 2020-11-28 04:18

Is there a query for calculating how many distinct values a field contains in DB.

f.e I have a field for country and there are 8 types of country values (spain, engl

6条回答
  •  广开言路
    2020-11-28 04:28

    I use this query:

    var collection = "countries"; var field = "country"; 
    db[collection].distinct(field).forEach(function(value){print(field + ", " + value + ": " + db.hosts.count({[field]: value}))})
    

    Output:

    countries, England: 3536
    countries, France: 238
    countries, Australia: 1044
    countries, Spain: 16
    

    This query first distinct all the values, and then count for each one of them the number of occurrences.

提交回复
热议问题