使用聚合对嵌套列进行sorting

我有以下查询使用聚合框架在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) { //... }); 

最后,我想使用comments数组中的creationDate对logging进行sorting。 我已经使用comments.creationDate但它不工作!

使用聚合框架对项目进行sorting的正确方法是什么?

您需要将您的$sort上的creationDate移动到$group上面,以便使用$push影响comments数组的构build顺序。 现在,您正在对整套文档进行sorting,而不是数组。

 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) { //... });