使用聚合对嵌套列进行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) { //... });