定义
返回在窗口内对应指定百分位数的百分位数值数组。
注意
消歧
本页介绍了用作 窗口函数 时的 $percentile。
您还可以在这些其他上下文中使用 $percentile:
$percentile (accumulator), 它返回一个聚合数组,其中包含一组输入文档的百分位数值。$percentile (expression), 用于计算输入值数组中的百分位数值。
语法
{ $setWindowFields: { ... output: { <field>: { $percentile: { input: <expression>, p: [ <expression1>, <expression2>, ... ], method: <string> }, } } }}选项
字段 | 类型 | 说明 |
|---|---|---|
| 表达式(expression) |
|
| 表达式(expression) |
|
| 字符串 | MongoDB 用于计算百分位数的方法。该方法必须是 |
行为
在 $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中。使用
$project以在输出中包含title、year、imdb_rating和top10PctRatingForYear字段。使用
$sort先按年份升序,再按 IMDB 评分降序排列结果。