对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$top(累加器运算符)

$top

根据指定的排序顺序返回群组内第一个元素。

注意

消歧

本页介绍了 $top 用作 累加器 时的情况。累加器返回对一组输入文档计算的单一聚合值。

您还可以在这些其他上下文中使用 $top:

{ $top: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> }}
字段
必要性
说明

sortBy

必需

指定结果的顺序,语法类似于 $sort。

输出

必需

表示组中每个元素的输出,可以是任何表达式。

考虑以下聚合,该聚合从一组分数中返回最高分的文档:

  • $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 数据类型的顺序来确定顺序。 例如,考虑一个其值由字符串和数字组成的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 } } } } }] )

示例管道:

  • 使用 $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 } }] )

示例管道:

  • 使用 $match 过滤器出属于 G、PG、PG-13 和 R 类别的电影,并且 IMDb 评分为正值。

  • 使用 $group 按 rated 对结果分组。

  • 使用 $top 返回每个类别评分最高的电影。

  • 指定 $top 和 output : ["$title", "$imdb.rating"] 输出的字段。

  • 使用 sortBy: { "imdb.rating": -1 } 在每个组中按 IMDb 评分以降序对电影进行排序,从而确定 $top 返回的电影。

  • 使用 $sort 按评级类别字母顺序对结果进行排序。

给本页内容打分