Search code examples
arraysdatabasemongodbcountaggregation

MongoDB count different values in multiple arrays


I want to count how often a unique value occurs. I have multiple arrays with objects like:

{“value”:”a”,”begin”:0,”end”:12}

but I only need the “value” part of the object so I projected only the values so the result of my projection looks like this but with multiple arrays:

{“values”:[{“value”:”a”},{“value”:”b”},{“value”:”b”}]}

My goal is to get a result array with all different values and how often they occurred in all multiple arrays:

[{“value”:”a”,”count”:1},{“value”:”b”,”count”:2}]


Solution

  • You can simply do:

    db.collection.aggregate([
      {$unwind: "$values"},
      {$group: {_id: "$values.value", count: {$sum: 1}}}
    ])
    

    See how it works on the playground example