定义
返回通过数字大量计算得出的一个或多个百分位数位数。
注意
消歧
This page describes $percentile when used as an expression, which calculates percentile values over an array of input values.
您还可以在其他上下文中使用 $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' } } } } ] )
在前面的管道中,带有 $percentile 的 $project 计算每个学生的 scores大量的第 25、50 和 75 百分百分位数,并将它们作为 testPercentiles 返回。