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