定义
返回在数字数组上计算得出的一个或多个百分位数。
注意
消歧
本页介绍了 $percentile 在 表达式 中的用法,它可以计算输入值数组的百分位数。
您还可以在这些其他上下文中使用 $percentile:
$percentile (accumulator), 通过对一组输入文档进行聚合来返回百分位数值。$percentile (window function),用于在$setWindowFields阶段返回特定窗口中文档的百分位数值数组。
语法
{ $percentile: { input: <expression>, p: [ <expression1>, <expression2>, ... ], method: <string> }}选项
字段 | 类型 | 说明 |
|---|---|---|
| 阵列 | 可以为以下任一项:
|
| 表达式(expression) |
|
| 字符串 | MongoDB 用于计算百分位数的方法。该方法必须是 |
行为
作为表达式使用时,$percentile 始终使用精确的百分位数计算算法,而不是近似算法,即使指定了 method: 'approximate' 也是如此。这是因为表达式在有界大小的数组上运行,在这种情况下,可以将所有输入值保留在内存中。
例子
创建一个 testScores 集合:
db.testScores.insertMany( [ { studentId: "2345", scores: [ 62, 81, 80, 75, 68 ] }, { studentId: "2356", scores: [ 60, 83, 79, 72, 65 ] }, { studentId: "2358", scores: [ 67, 82, 78, 70, 84 ] }, { studentId: "2367", scores: [ 64, 72, 77, 58, 91 ] }, { studentId: "2369", scores: [ 60, 53, 72, 85, 63 ] }] )以下管道使用 $percentile 计算每位学生的 25、50 和 75 百分位数测试分数:
db.testScores.aggregate( [ { $project: { _id: 0, studentId: 1, testPercentiles: { $percentile: { input: "$scores", p: [ 0.25, 0.5, 0.75 ], method: 'approximate' } } } }] )在前面的管道中,$project 使用 $percentile 计算每个学生的 scores 数组的第 25、50 和 75 百分位数,并将其作为 testPercentiles 返回。