在猫鼬聚合框架中按日期排序 [英] Sort by date in mongoose aggregation framework
问题描述
我正在使用猫鼬在nodejs + mongodb项目上工作.现在我遇到一个我不知道答案的问题. 我正在使用聚合框架来获取分组结果.分组是在排除时间数据字段的日期上完成的,例如:"2013 02 06".代码如下:
Im working on a nodejs+mongodb project using mongoose. Now I have come across a question I don't know the answer to. I am using aggregation framework to get grouped results. The grouping is done on a date excluding time data field like: "2013 02 06". Code looks like this:
MyModel.aggregate([
{$match: {$and: [{created_date: {$gte: start_date}}, {created_date: {$lte: end_date}}]}},
{$group: {
_id: {
year: {$year: "$created_at"},
month: {$month: "$created_at"},
day: {$dayOfMonth: "$created_at"}
},
count: {$sum: 1}
}},
{$project: {
date: {
year: "$_id.year",
month:"$_id.month",
day:"$_id.day"
},
count: 1,
_id: 0
}}
], callback);
除未排序的结果外,分组结果是完美的.这是输出示例:
The grouped results are perfect, except that they are not sorted. Here is an example of output:
[
{
count: 1,
date: {
year: 2013,
month: 2,
day: 7
}
},
{
count: 1906,
date: {
year: 2013,
month: 2,
day: 4
}
},
{
count: 1580,
date: {
year: 2013,
month: 2,
day: 5
}
},
{
count: 640,
date: {
year: 2013,
month: 2,
day: 6
}
}
]
我知道排序是通过添加以下内容来完成的:{$sort: val}
.但是现在我不确定val
应该是什么,因此结果将按日期排序,因为我的分组键是一个由3个值构成的对象构成日期.有谁知道如何做到这一点?
I know the sorting is done by adding this: {$sort: val}
. But now I'm not sure what should be the val
so the results would be sorted by date as my grouping key es an object of 3 values constructing the date. Does anyone know how this could be accomplished?
编辑 尝试了一下,它就起作用了:)
EDIT Have tryed this and it worked :)
{$sort: {"date.year":1, "date.month":1, "date.day":1}}
推荐答案
此问题似乎有一个非常简单的答案:)只需按多个嵌套列进行排序,如下所示:
It appears that this question has a very simple answer :) Just need to sort by multiple nesteed columns like this:
{$sort: {"date.year":1, "date.month":1, "date.day":1}}
这篇关于在猫鼬聚合框架中按日期排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!