【问题标题】:MongoDB sort by multiple fieldsMongoDB按多个字段排序
【发布时间】:2014-10-21 01:27:02
【问题描述】:

我正在制作可以投票的帖子。每张选票都会影响帖子的得分。每个帖子都有一个 id 和一个分数。我正在尝试查询 MongoDB 以查找热门帖子。我想通过按帖子发布时间排序,取最近的 100 个,然后按分数对这 100 个排序。 Post 是一个带有 _id 和 score 的 mongoose Schema。我试过了:

Post.find({}).sort({_id: -1}).limit(100).sort({score: -1}).exec(function(err, posts) {
    if(err){
        res.status(500).send(err);
    } else {
        //do stuff
    }
});

但是,这会导致错误。如何修复它或以不同的方式实现我想要的排序?谢谢

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您可以使用aggregate 执行多个排序阶段:

    Post.aggregate([
        {$sort: {_id: -1}},
        {$limit: 100},
        {$sort: {score: -1}}
    ], function(err, posts) { ...});
    

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2015-01-20
      • 2016-12-23
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多