Mongodb Group By Date And Add Properties To Each Other

Viewed 7

I have a collection filled with posts and their engagements. I want to group the documents by date and sum the values of the properties here's an example:

const response = await this._engagementsModel.aggregate([
    {
        $project: {
            _id: 0,
            post: 0,
            date: '$createdAt',
            positiveReaction: 1,
            negativeReaction: 1,
            totalReactions: 1,
        }
    },
    {
        $group: {
            _id: '$date',
            positiveEngagements: { $first: '$positiveEngagements' },
            negativeEngagements: { $first: '$negativeEngagements' },
            totalEngagements: { $first: '$totalEngagements' },
        }
     }
]);

for the following inputs:

    // document 1
    {    
      _id: 'some_id',
      createdAt: '2022-09-07T11:57:01.594+00:00',
      post: 'post_url',
      positiveEngagements: 6711
      negativeEngagements: 3
      totalEngagements: 6714
    }
    // document 2
    {    
      _id: 'some_id',
      createdAt: '2022-09-07T11:57:01.594+00:00',
      post: 'post_url',
      positiveEngagements: 1175
      negativeEngagements: 0
      totalEngagements: 1175
    }

I get this output, it returns the first document's values:

{    
  _id: '2022-09-07T11:57:01.594+00:00'
  positiveEngagements: 6711
  negativeEngagements: 3
  totalEngagements: 6714
}

Now here's the result that I want to get:

    {    
      _id: '2022-09-07T11:57:01.594+00:00'
      positiveEngagements: 6711 + 1175
      negativeEngagements: 3 + 0
      totalEngagements: 6714 + 1175
    }
0 Answers
Related