Mongoose聚合没有排序日期

时间:2015-05-15 10:52:16

标签: javascript node.js mongodb mongoose aggregation-framework

有人可以帮我理解为什么这个聚合查询没有按照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
  }
 }}
])

1 个答案:

答案 0 :(得分:1)

  

为什么这个聚合查询没有按照created_at日期对结果进行排序?

无法保证$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 }
 }
])