使用聚合对嵌套列进行排序

时间:2014-07-19 07:55:31

标签: node.js mongodb mongoose

我在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但它不起作用!

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

1 个答案:

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