Home > Blockchain >  How to group objects with the same key using mongodb aggregation
How to group objects with the same key using mongodb aggregation

Time:10-20

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

CodePudding user response:

$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

  • Related