mongodb count num of distinct values per field/key

前端 未结 6 1968
小蘑菇
小蘑菇 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:39

    MongoDB has a distinct command which returns an array of distinct values for a field; you can check the length of the array for a count.

    There is a shell db.collection.distinct() helper as well:

    > db.countries.distinct('country');
    [ "Spain", "England", "France", "Australia" ]
    
    > db.countries.distinct('country').length
    4
    

提交回复
热议问题