我觉得db.grades.find、sort、limit 极其简单。我喜欢。如果需要它使用聚合管道来完成更高级的工作,那么只需将聚合视为一组步骤。它不像 SQL(你将所有内容都塞进一个语句中)。
相反,请使用聚合管道分层构建您的查询。执行以下一次添加一个元素,你就会明白我的意思了。
db.grades.aggregate(
{'$match':{'score':{'$gte':65}}},
{'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}},
{'$sort':{'scoreMax':-1}},
{'$limit':1}
)
$match 拉取分数 >= 65。仅使用该元素执行您的管道,您将看到所有匹配的分数。
db.grades.aggregate(
{'$match':{'score':{'$gte':65}}}
)
$group 获得每个 student_id 的最高分(我认为,这就是您的教授希望您使用的)
db.grades.aggregate(
{'$match':{'score':{'$gte':65}}},
{'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}}
)
$sort 将汇总的学生列表按顺序排列(从最聪明到最愚蠢)
db.grades.aggregate(
{'$match':{'score':{'$gte':65}}},
{'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}},
{'$sort':{'scoreMax':-1}}
)
$limit 只提取最优秀的学生和她的分数。
db.grades.aggregate(
{'$match':{'score':{'$gte':65}}},
{'$group':{'_id':'$student_id', 'scoreMax':{'$max':'$score'}}},
{'$sort':{'scoreMax':-1}},
{'$limit':1}
)