定义
根据指定的排序顺序返回群组内第一个元素。
注意
消歧
本页介绍了 $top 用作 累加器 时的情况。累加器返回对一组输入文档计算的单一聚合值。
您还可以在这些其他上下文中使用 $top:
$top (expression operator),根据指定的排序顺序返回数组的顶部元素。$top (window function),用于在$setWindowFields阶段中返回特定窗口中文档的顶部元素。
语法
{ $top: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> }}字段 | 必要性 | 说明 |
|---|---|---|
sortBy | 必需 | 指定结果的顺序,语法类似于 |
输出 | 必需 | 表示组中每个元素的输出,可以是任何表达式。 |
行为
Null 和缺失值
考虑以下聚合,该聚合从一组分数中返回最高分的文档:
$top不筛选空值。$top将缺失值转换为空。
db.aggregate( [ { $documents: [ { playerId: "PlayerA", gameId: "G1", score: 1 }, { playerId: "PlayerB", gameId: "G1", score: 2 }, { playerId: "PlayerC", gameId: "G1", score: 3 }, { playerId: "PlayerD", gameId: "G1"}, { playerId: "PlayerE", gameId: "G1", score: null } ] }, { $group: { _id: "$gameId", playerId: { $top: { output: [ "$playerId", "$score" ], sortBy: { "score": 1 } } } } }] )在本例中:
$documents创建包含玩家分数的字面文档。$group按gameId对文档进行分组。此示例只有一个gameId、G1。PlayerD分数缺失,且PlayerE的score为空。这些值都被视为空值。playerId和score字段指定为output : ["$playerId"," $score"],并以数组值形式返回。用
sortBy: { "score": 1 }指定排序顺序。PlayerD和PlayerE并列为顶元素。PlayerD作为顶级score返回。要对多个空值进行更具确定性的平局决胜行为,请向
sortBy添加更多字段。
BSON 数据类型排序
对不同类型进行排序时,将使用BSON 数据类型的顺序来确定顺序。 例如,考虑一个其值由字符串和数字组成的collection。
在升序排序中,字符串值排在数值之后。
在降序排序中,字符串值排在数值之前。
在本例中:
PlayerA有一个整数分数。PlayerB有一个字符串"2"分数。PlayerC有一个空字符串分数。
由于排序是降序 { "score": -1 },string 值在 PlayerA 的数值分数之前排序。$top 排序后返回第一个元素,即 PlayerB:
db.aggregate( [ { $documents: [ { playerId: "PlayerA", gameId: "G1", score: 1 }, { playerId: "PlayerB", gameId: "G1", score: "2" }, { playerId: "PlayerC", gameId: "G1", score: "" } ] }, { $group: { _id: "$gameId", playerId: { $top: { output: [ "$playerId", "$score" ], sortBy: { "score": -1 } } } } }] )示例
本页上的示例使用来自 sample_mflix 数据集的数据。有关如何将此数据集加载到您的自管理 MongoDB 部署中的详细信息,请参阅 加载示例数据集。如果您对示例数据库进行了任何修改,您可能需要删除并重新创建数据库,才能运行此页面上的示例。
查找某个类别中的最高评级
可以使用 $top 累加器查找某个类型中评分最高的电影。
db.movies.aggregate( [ { $match: { genres: "Comedy", "imdb.rating": { $gt: 0 } } }, { $group: { _id: "Comedy", highestRatedMovie: { $top: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } }] )示例管道:
在多个评级中找出顶部评级
您可以使用 $top 累加器查找每个电影评分类别中评分最高的电影。
db.movies.aggregate( [ { $match: { rated: { $in: [ "G", "PG", "PG-13", "R" ] }, "imdb.rating": { $gt: 0 } } }, { $group: { _id: "$rated", highestRatedMovie: { $top: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } }, { $sort: { _id: 1 } }] )示例管道: