3

I have collection of documents that are output from aggregation and they were grouped by name. Each object should be accessed by name property and its unique. Each of them contain values, I want to get count of each value in their array without losing uniqueness of name property.

{
  name: "Foo",
  values: ["FOO", "BAR", "FOO"]
},
{
  name: "Bar",
  values: ["BAZ", "BAR", "BAR"]
},
{
  name: "Baz",
  values: ["BAZ", "BAZ", "BAZ"]
}

I want to turn their array of strings into array of objects. Each of these objects has value that represents one of string values and count of how often was that value repeated in array of strings as shown below:

{
  name: "Foo",
  values: [
    val: "FOO", count: 2,
    val: "BAR", count: 1 
  ]
},
{
  name: "Bar",
  values: [
    val: "BAR", count: 2,
    val: "BAZ", count: 1
  ]
},
{
  name: "Baz",
  values: [
    val: "BAZ", count: 3
  ]
}

1 Answer 1

5

you can achieve this with the aggregation framework like this :

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

this output:

{ "_id" : "Bar", "values" : [ { "val" : "BAZ", "count" : 1 }, { "val" : "BAR", "count" : 2 } ] }
{ "_id" : "Foo", "values" : [ { "val" : "FOO", "count" : 2 }, { "val" : "BAR", "count" : 1 } ] }
{ "_id" : "Baz", "values" : [ { "val" : "BAZ", "count" : 3 } ] }

try it online: mongoplayground.net/p/ta2Jkqtkc3G

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.