1

I have these types of objects in the DB.

[
  { data: { key: 'A', value: 'one' } },
  { data: { key: 'A', value: 'one' } },
  { data: { key: 'A', value: 'two' } },
  { data: { key: 'A', value: 'one' } }
]

I tried the following Aggregate

{
  $group: {
   _id: { key: "$data.key", value: "$data.value" },
   count: { $sum: 1 },
  }
},

And I got the following result:

[
 { _id: { key: 'A', value: 'two' }, count: 1 },
 { _id: { key: 'A', value: 'one' }, count: 3 }
]

How can I structure my pipeline to get the results I want?

[
 {
   key: 'A',
   result : [
      { value: 'one', count: 3 },
      { value: 'two', count: 1 },
    ]
 }
]

1 Answer 1

2

$group twice

db.collection.aggregate([
  {
    $group: {
      _id: {
        key: "$data.key",
        value: "$data.value"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $group: {
      _id: "$_id.key",
      result: {
        $push: {
          value: "$$ROOT._id.value",
          count: "$$ROOT.count"
        }
      }
    }
  }
])

mongoplayground

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.