我在Mongoose中使用聚合框架进行以下查询:
Comment.aggregate([{
$match: {
isActive: true
}
}, {
$group: {
_id: {
year: {
$year: "$creationDate"
},
month: {
$month: "$creationDate"
},
day: {
$dayOfMonth: "$creationDate"
}
},
comments: {
$push: {
comment: "$comment",
username: "$username",
creationDate: "$creationDate",
}
}
}
}, {
$sort: {
'comments.creationDate': -1
}
}, {
$limit: 40
}], function (err, comments) {
//...
});
最后,我想使用creationDate
数组中的comments
对记录进行排序。我使用过comments.creationDate
但它不起作用!
使用聚合框架对项目进行排序的正确方法是什么?
答案 0 :(得分:1)
您需要将$sort
移至creationDate
上$group
以上,以便它影响使用comments
构建$push
数组的顺序。正如你现在所做的那样,你要整理整个文档集,而不是数组。
Comment.aggregate([{
$match: {
isActive: true
}
}, {
$sort: {
creationDate: -1
}
}, {
$group: {
_id: {
year: {
$year: "$creationDate"
},
month: {
$month: "$creationDate"
},
day: {
$dayOfMonth: "$creationDate"
}
},
comments: {
$push: {
comment: "$comment",
username: "$username",
creationDate: "$creationDate",
}
}
}
}, {
$limit: 40
}], function (err, comments) {
//...
});