0

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}]

4
  • You can use $unwind and $group with {$sum:1} Commented Sep 19, 2022 at 12:25
  • i dont know where my error is but i cant unwind the arrays. Would it be {$unwind: {path: "values"}? Commented Sep 19, 2022 at 13:20
  • You can use {$unwind: "$values"}. Please provide few sample documents and I'll show you Commented Sep 19, 2022 at 14:12
  • For example i would get 2 Documents with following data. { "values": [ "value": "a", "value": "b", "value": "c", "value": "a", "value": "b", "value": "c" ] } { "values": [ "value": "a", "value": "b", "value": "d", "value": "g", "value": "d", "value": "c" ] } And as result i need: { {"value": "a", "count": 3}, {"value": "b", "count": 3}, {"value": "c", "count": 3}, {"value": "d", "count": 2}, {"value": "g", "count": 1}, } Commented Sep 19, 2022 at 14:37

1 Answer 1

1

You can simply do:

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

See how it works on the playground example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.