Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
  }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading