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

$percentile (表达式)

$percentile

返回在数字数组上计算得出的一个或多个百分位数。

注意

消歧

本页介绍了 $percentile 在 表达式 中的用法,它可以计算输入值数组的百分位数。

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

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

input

阵列

可以为以下任一项:

  • 解析为数组的表达式。示例,$scores,其中文档字段 $scores 包含一个数值数组。

  • 一个表达式数组,其中每个表达式的求值结果均为数值。示例,[ "$field1", "$field2", "$field3" ]。

$percentile 计算数组中所有数值的百分位数值。非数值被忽略。

p

表达式(expression)

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

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

method

字符串

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

作为表达式使用时,$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 返回。

给本页内容打分