sort by date with aggregate request in mongodb is not sorting properly

Viewed 27

I'm trying to get the sum or records by groping its created date. Following is how the date looks in DB date:2022-05-18T22:16:59.864+00:00

My NodeJs/Express Code is as follows

const totalClicks = await StatModel.aggregate([
  { $match: { campaign_id: id } },
  {
    $group: {
      _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
      count: { $sum: 1 },
    },
  },
  { $sort: { date: -1 } },
]);

And following is the output

[{"_id":"2022-05-17","count":20},{"_id":"2022-05-15","count":9},{"_id":"2022-05-19","count":37},{"_id":"2022-05-18","count":12}]
1 Answers

Yes, @varman your solution worked. Following is the updated code.

const totalClicks = await StatModel.aggregate([
  { $match: { campaign_id: id } },
  {
    $group: {
      _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
      count: { $sum: 1 },
    },
  },
  { $sort: { _id: 1 } },
]);
Related