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

$bottomN(窗口函数)

$bottomN

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

注意

消歧

本页介绍了用作窗口函数的 $bottomN。

您也可以使用 $bottomN (accumulator),它会根据指定的排序顺序返回群组内位于最后的 n 元素。

{
$setWindowFields: {
...
output: {
<field>: {
$bottomN: {
n: <expression>,
output: <expression>,
sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }
},
window: {
documents: [ <lower boundary>, <upper boundary> ]
}
}
}
}
}
字段
必要性
说明

n

必需

要返回的结果数。必须解析为正整数值。

如果窗口包含的元素少于 n 个,$bottomN 将返回窗口中的所有元素。

output

必需

确定窗口中每个文档的输出。可以是任何表达式。

sortBy

必需

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

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

此示例使用 $bottomN窗口函数返回每部电影以及同一年上映的三部收视率最低的电影。

db.movies.aggregate( [
{
$unwind: "$genres"
},
{
$match: {
genres: "Action",
rated: "PG-13",
"imdb.rating": { $lte: 5 },
year: { $in: [ 2000, 2001, 2002 ] }
}
},
{
$setWindowFields: {
partitionBy: "$year",
output: {
lowestThreeMovies: {
$bottomN: {
sortBy: { "imdb.rating": -1, title: 1 },
output: [ "$title", "$imdb.rating" ],
n: 3
},
window: {
documents: [ "unbounded", "unbounded" ]
}
}
}
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
"imdb.rating": 1,
lowestThreeMovies: 1
}
}
] )

在前面的示例中:

  • $unwind 解构 genres大量,以便每个电影文档仅包含一个类型。

  • $match 将输入限制为评级为 PG-13、imdb.rating 值为 5 或更低以及在 2000、2001 或 2002 上映的 Action 电影。

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

  • window: { documents: [ "unbounded", "unbounded" ] } 跨越整个年份分区,因此 $bottomN 在确定收视率最低的三部电影时会考虑当年的所有文档。

  • $bottomN 使用 sortBy: { "imdb.rating": -1, title: 1 } 按 IMDb 分数对电影进行排名,并使用 title 作为决胜局。同一年的每个文档都具有相同的 lowestThreeMovies 值。

  • $project 删除不需要的字段以突出显示窗口函数结果。

给本页内容打分

在此页面上