MongoDB Max,Sort和Limit

时间:2015-12-06 13:14:16

标签: mongodb

我尝试使用find(不是聚合)给我一个测试的学生最高分。基本上是按学生排序,找到该学生的最高分,然后对结果集进行排序。这是数据:

 { "_id" : 1, "name" : "Pat", "score" : 97 }
 { "_id" : 1, "name" : "Pat", "score" : 92 }
 { "_id" : 2, "name" : "Pat", "score" : 89 }
 { "_id" : 3, "name" : "Ken", "score" : 91 }
 { "_id" : 4, "name" : "Ken", "score" : 81 }

我正在寻找这样的结果(只返回学生最高分):

{ "_id" : 1, "name" : "Pat", "score" : 97 }
{ "_id" : 2, "name" : "Ken", "score" : 91 }

我尝试了很多不同的组合,但无法让它发挥作用。我在SQL中知道我是怎么做到的。这是我当前的代码,它只是对它进行排序:

 db.grades.find().sort({score: -1})

1 个答案:

答案 0 :(得分:-2)

您可以使用:

db.grades.find().sort('-score').distinct('name').sort('score')
相关问题