猫鼬聚合不排序日期

Mongoose aggregation not sorting dates

谁能帮我理解为什么这个聚合查询没有按 created_at 日期对结果进行排序?

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
  }
 }}
])

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

无法保证 $group 稳定(即:尽可能维持秩序)。

因此,如果您需要按特定顺序排列结果,则应使用 $sort 步骤作为管道的最后一步。类似的东西(未经测试):

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 }
 }
])