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

$percentile (窗口函数)

$percentile

返回在窗口内对应指定百分位数的百分位数值数组。

注意

消歧

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

您还可以在这些其他上下文中使用 $percentile:

{ $setWindowFields: { ... output: { <field>: { $percentile: { input: <expression>, p: [ <expression1>, <expression2>, ... ], method: <string> }, } } }}
字段
类型
说明

input

表达式(expression)

$percentile 计算百分位数值的字段。input 必须是计算结果为数字类型的表达式。如果表达式未评估为数值类型,则 $percentile 计算将忽略该值。

p

表达式(expression)

$percentile 计算 p 中每个元素的百分位数。这些元素指定要计算的分位数,并且必须是在 0.0 到 1.0(包含在内)范围内的数值。

$percentile 按照与 p 中元素相同的顺序返回结果。

method

字符串

MongoDB 用于计算百分位数的方法。该方法必须是 'approximate'。

在 $setWindowFields 中,$percentile 为每个文档返回一个结果,但结果是通过文档窗口计算得出的。

当作为窗口函数使用时,$percentile 始终使用精确的百分位数计算算法,而不是近似算法,即使指定了 method: 'approximate' 也是如此。

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

以下示例在 $setWindowFields 阶段中使用 $percentile 查找 2002 年至 2004 年每年 IMDB 评级前 10% 的动作类电影。

db.movies.aggregate( [ { $match: { year: { $in: [ 2002, 2003, 2004 ] }, genres: "Action", "imdb.votes": { $gte: 5000 }, } }, { $setWindowFields: { partitionBy: "$year", output: { top10PctRatingForYear: { $percentile: { input: "$imdb.rating", p: [ 0.9 ], method: "approximate" }, window: { documents: [ "unbounded", "unbounded" ] } } } } }, { $match: { $expr: { $gte: [ "$imdb.rating", { $arrayElemAt: [ "$top10PctRatingForYear", 0 ] } ] } } }, { $project: { _id: 0, title: 1, year: 1, imdb_rating: "$imdb.rating", top10PctRatingForYear: 1 } }, { $sort: { year: 1, imdb_rating: -1 } }] )

前面的管道:

  • 使用 $match 过滤器来过滤于 2002、2003 或 2004 年发行的操作片,至少有 5,000 张 IMDB 票数。

  • 使用 $setWindowFields 按 year 对电影进行分区。在每个分区内,$percentile 操作符使用 p: [0.9] 和无界窗口计算第 90 个百分位数 IMDB 评级,并存储在 top10PctRatingForYear 中。

  • 使用 $match 和 $expr 作为过滤器来过滤电影,其 IMDB 评分大于或等于当年的第 90 个百分位数评分。

  • 使用 $project 以在输出中包含 title、year、imdb_rating 和 top10PctRatingForYear 字段。

  • 使用 $sort 先按年份升序,再按 IMDB 评分降序排列结果。

给本页内容打分