【问题标题】:How to sort by a specific criteria the top X documents already sorted with mongodb?如何按特定标准对已使用 mongodb 排序的前 X 文档进行排序?
【发布时间】:2015-11-20 09:50:15
【问题描述】:

对我来说,提出这个问题有点困难。问题是,我需要获得 100 个评分最高的文档,然后按照另一个标准对结果进行排序。

我是 mongodb 的初学者,我天真地尝试过类似的东西:

db.myCollection
  .find()                                 // get all the data
  .sort({ "statistics.average": -1 })     // sort by rating
  .limit(100)                             // get the 100 best rated
  .sort({ "statistics.foobar": -1 })      // sort the result by the second criteria

但它不起作用,看起来最后一次排序是对所有数据完成的。

如何正确创建符合我需要的查询?

【问题讨论】:

    标签: mongodb sorting mongodb-query aggregation-framework


    【解决方案1】:

    Mongo 在限制结果之前应用排序,无论您在游标上调用排序和限制的顺序如何,但使用 .aggregate() 方法将给出预期结果。

    db.mycollection.aggregate([
        { "$sort": { "statistics.average": -1 } },
        { "$limit": 100 }, 
        { "$sort": { "statistics.foobar": -1 } }
    ]) 
    

    【讨论】:

      【解决方案2】:
      db.myCollection
        .find()                                 // get all the data
        .sort({ "statistics.average": -1 ,"statistics.foobar": -1 })     // sort by rating followed by foobar
        .limit(100) // get the 100 best rated
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-10
        • 2011-04-11
        • 2014-08-21
        相关资源
        最近更新 更多