Ross J
Ross J

Reputation: 382

Mongoose aggregation not sorting dates

Can anyone help me understand why this aggregation query is not sorting the results by their created_at date?

User.aggregate([
 // Get only records created in the last 30 days
 { $match: {
  "created_at":{ $gt: new Date(today.getTime() - 1000*60*60*24*30) }
 }},
 //Sort the results by signup date
 { $sort : {
  "created_at" : -1 }
 },
 // Get the year, month and day from the createdTimeStamp
 { $project: {
  "year":{ $year:"$created_at" },
  "month":{ $month:"$created_at" },
  "day": { $dayOfMonth:"$created_at" }
 }},
 // Group by year, month and day and get the count
 { $group: {
  _id:{
   year:"$year",
   month:"$month",
   day:"$day"
  },
  "count":{
   $sum:1
  }
 }}
])

Upvotes: 0

Views: 466

Answers (1)

Sylvain Leroux
Sylvain Leroux

Reputation: 52000

why this aggregation query is not sorting the results by their created_at date?

There is no guarantee for $group to being stable (i.e.: maintain order if possible).

So, if you need your result in some particular order, you should use the $sort step as the last step of your pipeline. Something like that (untested):

User.aggregate([
 // Get only records created in the last 30 days
 { $match: {
  "created_at":{ $gt: new Date(today.getTime() - 1000*60*60*24*30) }
 }},
 // Get the year, month and day from the createdTimeStamp
 { $project: {
  "year":{ $year:"$created_at" },
  "month":{ $month:"$created_at" },
  "day": { $dayOfMonth:"$created_at" }
 }},
 // Group by year, month and day and get the count
 { $group: {
  _id:{
   year:"$year",
   month:"$month",
   day:"$day"
  },
  "count":{
   $sum:1
  }
 }},

 //Sort the results by year-month-day of signup date
 { $sort : {
  "year" : -1,
  "month": -1,
  "day": -1 }
 }
])

Upvotes: 1

Related Questions