Home > Net >  Whats the best way to aggregate for grouping by particular key and adding the values?
Whats the best way to aggregate for grouping by particular key and adding the values?

Time:11-15

I have a collection in my mongodb named events. Here are few data from it:

[{
  _id: 100,
  streamer_id: a01,
  viewers: 4,
  title: "Event 1"
},{
  _id: 101,
  streamer_id: a01,
  viewers: 7,
  title: "Event 2"
},
{
  _id: 103,
  streamer_id: a02,
  viewers: 3,
  title: "Stream"
},

I basically want the streamer_id to be grouped and the number of viewers to be added. What's the best way to do it with aggregation?

Havent tried anything yet cause I have no clue how to proceed with this. But this is what I expect:

[{
  _id: any id,
  streamer_id: a01,
  total_viewers: 11
},{
  _id: any id,
  streamer_id: a02,
  total_viewers: 3
},

CodePudding user response:

Please attempt the problem first in future.

But here is a simple approach with $group and $sum. You can also use $project to format your documents as you would like it to be.

Working example: https://mongoplayground.net/p/Ucb2EWgC_Y5

Query:

db.collection.aggregate([
  {
    $group: {
      _id: {
        streamer_id: "$streamer_id",
      },
      total_viewers: {
        $sum: "$viewers"
      }
    }
  },
  {
    $project: {
      _id: 0,
      streamer_id: "$_id.streamer_id",
      total_viewers: 1
    }
  }
])

Result:

[
  {
    "streamer_id": "a01",
    "total_viewers": 11
  },
  {
    "streamer_id": "a02",
    "total_viewers": 3
  }
]
  • Related