mongodb count num of distinct values per field/key

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

    You can leverage on Mongo Shell Extensions. It's a single .js import that you can append to your $HOME/.mongorc.js, or programmatically, if you're coding in Node.js/io.js too.

    Sample

    For each distinct value of field counts the occurrences in documents optionally filtered by query

    > db.users.distinctAndCount('name', {name: /^a/i})

    {
      "Abagail": 1,
      "Abbey": 3,
      "Abbie": 1,
      ...
    }
    

    The field parameter could be an array of fields

    > db.users.distinctAndCount(['name','job'], {name: /^a/i})

    {
      "Austin,Educator" : 1,
      "Aurelia,Educator" : 1,
      "Augustine,Carpenter" : 1,
      ...
    }
    

提交回复
热议问题