【问题标题】:Sorting priority排序优先级
【发布时间】:2015-08-03 04:25:13
【问题描述】:

我在 MongoDB 数据库中有一个集合 Answers,我根据每个答案的支持数对文档进行排序。

Answers.find({}, {sort: {voteCount: -1}})

但是,其中一些答案是由教师发布的,它们应该排在“常规”答案之前。教师发布的答案有一个字段isInstructor: true。 如何检索我的答案列表,这些答案的排序方式是教师的答案排在第一位(也按voteCounts 排序),然后是正常答案(仍按voteCounts 排序)?

【问题讨论】:

  • 您可以显示具有预期输出的简单文档吗? db.collection.find().sort({'isInstructor': -1, voteCount: -1})呢?
  • 耶!不敢相信我这么愚蠢没有弄清楚这一点!谢谢:D

标签: mongodb sorting meteor


【解决方案1】:

好吧,正如我在评论中提到的,您必须按isInstructor 的降序和voteCount 的降序对您的answers 进行排序。另请注意,.find 的第二个参数是投影文档。因此,要对文档进行排序,您需要改用 cursor.sort 方法。

Answers.find().sort({ "isInstructor": -1, "voteCount": -1 })

【讨论】:

    【解决方案2】:

    使用光标的 sort() 方法,按顺序列出您想要排序的字段。 EG

    db.answers.find({}).sort(isInstructor: -1, voteCount: -1})
    

    参考:MongoDB Manual

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2011-10-09
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多