对于 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

7.0版本新增。

返回与指定的各百分位数一一对应的标量值数组。

可在以下阶段使用:

注意

消歧

本页描述了用作累加器时的 $percentile。累加器返回一群组输入文档的聚合值。

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

{
$percentile: {
input: <expression>,
p: [ <expression1>, <expression2>, ... ],
method: <string>
}
}

$percentile 采用以下字段:

字段
类型
必要性
说明

input

表达式(expression)

必需

$percentile 计算此数据的百分位数位数。 input 必须是计算结果为数字类型的表达式。如果表达式的计算结果不是数字类型,$percentile 计算将忽略该值。

p

表达式(expression)

必需

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

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

method

字符串

必需

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

用作累加器时,$percentile:

用作累加器时,$percentile 始终使用近似算法。由于 t-digest 近似算法中的伪随机性,每次运行时,针对同一数据集计算出的百分位数位数可能不同。此外,$percentile 返回的值可能与真实的统计百分位数略有不同。

本页上的示例使用 sample_mflix 数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载样本数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。

以下示例使用 $percentile累加器计算 Action 和 Drama 类型电影的第 50 和 90百分位数IMDB 评分:

db.movies.aggregate( [
{
$unwind: "$genres"
},
{
$match: {
genres: { $in: [ "Action", "Drama" ] },
"imdb.rating": { $exists: true }
}
},
{
$group: {
_id: "$genres",
ratingPercentiles: {
$percentile: {
input: "$imdb.rating",
p: [ 0.5, 0.9 ],
method: "approximate"
}
}
}
},
{
$sort: { _id: 1 }
}
] )

上述管道:

  • 使用 $unwind 为 genres大量中的每个类型创建单独的文档。

  • 使用 $match过滤分类为 Action 或 Drama 且具有 IMDB 评级字段的电影。

  • 按类型对电影进行分组。

  • 使用 $percentile 计算每个具有 p: [0.5, 0.9] 的类型的 IMDB 评分的第 50 和 90百分位数。

  • 使用 $sort 按类型名称对输出进行排序。

输出 ratingPercentiles大量包含两个值:每种类型的第 50 个百分位数和第 90 个百分位数位数。

给本页内容打分