定义
根据指定的排序顺序返回群组内第一个元素。
注意
消歧
本页描述了用作累加器时的 $top。累加器返回一群组输入文档的单个聚合值。
您还可以在 $setWindowFields 阶段使用 $top (window function) 返回特定窗口中文档的顶部元素。
语法
{ $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 } 降序排序,因此字符串值会排序在 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 } } } } } ] )
示例管道:
使用
$match过滤具有正面 IMDb 评分的喜剧电影。使用
$group将所有喜剧电影群组在单个"Comedy"群组键下。指定
$top和output : ["$title", "$imdb.rating"]输出的字段。使用
sortBy: { "imdb.rating": -1 }按 IMDb 评级(按降序排列)对群组内的电影进行排名,这决定了$top返回的电影。
查找多个评分中的最高评分
您可以使用 $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 } } ] )
示例管道: