定义
返回窗口中指定百分位数的百分位数数值大量。
注意
消歧
本页介绍了用作窗口函数的 $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]和存储在top10PctRatingForYear中的无界窗口计算第 90百分位数IMDB 评级。使用
$match和$expr过滤IMDB 评分大于或等于当年第 90百分位数评分的电影。使用
$project在输出中包含title、year、imdb_rating和top10PctRatingForYear字段。使用
$sort按年份升序排列结果,然后按 IMDB 评分降序排列。