Search code examples
mongodbmongooseaggregation-frameworkgrouping

Mongoose use aggregate to group documents by dates inside array


I am trying to get my head around .aggregate function in mongoose. I have the following Model and I try to count how many clicks have happened on each day.

var clickEvent = new Schema({
  createdAt: {type: Date},
  clicks: [{type: Date, _id: false}]
})

So Imagine I have the multiple documents like this:

[{
 createdAt: '2020-12-30T11:26:19.948+00:00',
 clicks: ['2021-01-27T15:58:37.109+00:00', '2021-01-28T15:58:37.109+00:00', 2021-01-28T15:58:37.109+00:00]
},

{
 createdAt: '2020-12-31T11:26:19.948+00:00',
  clicks: ['2021-01-24T15:58:37.109+00:00', '2021-01-22T15:58:37.109+00:00', 2021-01-28T15:58:37.109+00:00]
}]

I now want to get something back like

 [{day: '24-01-2021', totalClicks: 10}, {day: '25-01-2021', totalClicks: 2}]

I tried the following

 await Event.aggregate([
    {
      $group : {
        _id :{ $dateToString: { format: "%Y-%m-%d", clicks: "$date"} },
        list: { $push: "$$ROOT" },
        totalClicks: { $sum: 1 }
      }
    }
  ])
}

However this does not work. I believe this would only work if clicks would not be an array and just a single Date.

Thanks for your help!


Solution

    • $unwind deconstruct clicks array
    • $toDate clicks type from string to date type
    await Event.aggregate([
      { $unwind: "$clicks" },
      {
        $group: {
          _id: {
            $dateToString: {
              format: "%d-%m-%Y",
              date: { $toDate: "$clicks" }
            }
          },
          totalClicks: { $sum: 1 }
        }
      }
    ])
    

    Playground