对于 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

5.2版本新增。

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

注意

消歧

本页介绍了用作窗口函数的 $bottom。您还可以使用 $bottom (accumulator),它根据指定的排序顺序返回群组内的底部元素。

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

sortBy

必需

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

输出

必需

指定窗口中每个元素的输出。可以是任何表达式。

  • $bottom 不筛选空值。

  • $bottom 将缺失值转换为空。

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

此示例使用 $bottom 作为窗口函数来计算当前文档相对于同年评分最低的电影的评分。每个电影文档都包含该电影的评分和一个计算字段,该字段显示该电影的评分与同年评分最低的电影相比高出多少。

db.movies.aggregate( [
{
$match: {
year: { $in: [ 1980, 1981, 1982 ] },
"imdb.rating": { $exists: true, $ne: null },
genres: "Family",
rated: "PG"
}
},
{
$setWindowFields: {
partitionBy: "$year",
output: {
lowestRatedInYear: {
$bottom: {
output: { title: "$title", rating: "$imdb.rating" },
sortBy: { "imdb.rating": -1 }
},
window: {
documents: [ "unbounded", "unbounded" ]
}
}
}
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
rating: "$imdb.rating",
lowestRatedInYear: 1,
ratingAboveWorst: {
$subtract: [ "$imdb.rating", "$lowestRatedInYear.rating" ]
}
}
},
{
$limit: 10
}
] )

在本例中:

  • $match 阶段筛选 1980-1982 PG 级家庭电影。

  • $setWindowFields 按 year 对文档进行分区。

  • 窗口范围从 unbounded 到 unbounded,这意味着 $bottom 在确定评分最低的电影时会考虑分区中的所有文档。

  • $bottom 将每个分区中评分最低的电影作为包含 title 和 rating 字段的嵌入式文档返回。

  • $project 通过从每部电影的评分中减去最低评分来计算 ratingAboveWorst,显示每部电影的评分比当年表现最差的电影高出多少。

  • $limit 将输出限制为 10 文档。

这种方法保留了所有单独的电影文档,并将每个电影文档与当年表现最差的文档进行比较。

给本页内容打分