对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs 菜单

$bottom(累加器操作符)

$bottom

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

可在以下阶段使用:

注意

消歧

本页描述了用作累加器时的 $bottom。累加器返回一群组输入文档的单个聚合值。

您还可以在 $setWindowFields 阶段使用 $bottom (window function) 返回特定窗口中文档的底部元素。

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

sortBy

必需

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

输出

必需

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

$bottom 不会过滤掉 null 值,$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 }
}
}
}
}
] )

示例管道:

  • 使用 $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过滤具有 IMDb 评级的 2010-2012 范围的电影。

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

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

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

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

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

给本页内容打分