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

$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 删除不需要的字段以突出显示窗口函数结果。

给本页内容打分

在此页面上