对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs 菜单

$百分位数(表达式)

$percentile

返回通过数字大量计算得出的一个或多个百分位数位数。

注意

消歧

This page describes $percentile when used as an expression, which calculates percentile values over an array of input values.

您还可以在其他上下文中使用 $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'
}
}
}
}
] )

在前面的管道中,带有 $percentile 的 $project 计算每个学生的 scores大量的第 25、50 和 75 百分百分位数,并将它们作为 testPercentiles 返回。

给本页内容打分