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

$bottom(累加器操作符)

$bottom

根据指定的排序顺序返回组内的底部元素。

可在以下阶段使用:

注意

消歧

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

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

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

sortBy

必需

定义每个组中元素的排序顺序,语法类似于 $sort。不影响管道输出中文档的顺序。

输出

必需

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

$bottom 不过滤掉空值,并且 $bottom 将缺失值转换为 null。

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

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: { $bottom: { output: [ "$playerId", "$score" ], sortBy: { "score": -1 } } } } }] )
[ { _id: 'G1', playerId: [ 'PlayerD', null ] }]

在本例中:

  • $documents 创建包含玩家分数的字面文档。

  • $group 按 gameId 对文档进行分组。此示例只有一个 gameId、G1。

  • PlayerD 分数缺失,且 PlayerE 的 score 为空。这些值都被视为空值。

  • playerId 和 score 字段指定为 output : ["$playerId"," $score"],并以数组值形式返回。

  • 使用 sortBy: { "score": -1 } 指定排名顺序。

  • PlayerD 和PlayerE并列为底部元素。 PlayerD作为底部的score返回。

调用 $bottom 的聚合管道受 100 MB 限制。如果单个群组超过此限制,则聚合失败,并显示错误。

本页上的示例使用来自 sample_mflix 数据集的数据。有关如何将此数据集加载到您的自管理 MongoDB 部署中的详细信息,请参阅 加载示例数据集。如果您对示例数据库进行了任何修改,您可能需要删除并重新创建数据库,才能运行此页面上的示例。

您可以使用 $bottom 累加器在单个类别中查找评分最低的电影。

db.movies.aggregate( [ { $match : { genres: "Comedy" } }, { $group: { _id: "Comedy", lowestRatedMovie: { $bottom: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } }] )

示例管道:

  • 使用 $match 对单个类别的结果使用过滤器。在这种情况下,Comedy。

  • 使用 $group 将所有喜剧电影分组到单个 "Comedy" 分组密钥下。

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

  • 使用 sortBy: { "imdb.rating": -1 } 将每个组中评分最低的元素定义为底部元素。

  • 使用 $bottom 返回指定类型的评分最低的电影。

你可以使用 $bottom 累加器查找每年评分最低的电影。

db.movies.aggregate( [ { $match: { "imdb.rating": { $exists: true }, year: { $gte: 2010, $lte: 2012 } } }, { $group: { _id: "$year", lowestRatedMovie: { $bottom: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } }, { $sort: { _id: 1 } }] )

示例管道:

  • 使用 $match 过滤器从 2010 到 2012 年的电影,并具有 IMDb 评级。

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

  • 使用 $bottom 返回每年评分最低的电影。

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

  • 使用 sortBy: { "imdb.rating": -1 } 将每个组中评分最低的元素定义为底部元素。

  • 使用 $sort 按年份升序排序结果。

给本页内容打分