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

$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 份文档。

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

给本页内容打分