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

返回窗口中指定百分位数的百分位数数值大量。

注意

消歧

本页介绍了用作窗口函数的 $percentile。

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

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

input

表达式(expression)

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

p

表达式(expression)

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

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

method

字符串

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

在 $setWindowFields 中,$percentile 为每个文档返回一个结果,但该结果是在一个文档窗口上计算的。

用作窗口函数时,$percentile 始终使用准确的百分位数计算算法,而不是近似算法,即使指定了 method: 'approximate' 也是如此。

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

以下示例在 $setWindowFields 阶段使用 $percentile 查找从 2002 到 2004 每年 IMDB 评分位于前 10% 的动作片。

db.movies.aggregate( [
{
$match: {
year: { $in: [ 2002, 2003, 2004 ] },
genres: "Action",
"imdb.votes": { $gte: 5000 },
}
},
{
$setWindowFields: {
partitionBy: "$year",
output: {
top10PctRatingForYear: {
$percentile: {
input: "$imdb.rating",
p: [ 0.9 ],
method: "approximate"
},
window: { documents: [ "unbounded", "unbounded" ] }
}
}
}
},
{
$match: {
$expr: {
$gte: [
"$imdb.rating",
{ $arrayElemAt: [ "$top10PctRatingForYear", 0 ] }
]
}
}
},
{
$project: {
_id: 0,
title: 1,
year: 1,
imdb_rating: "$imdb.rating",
top10PctRatingForYear: 1
}
},
{
$sort: { year: 1, imdb_rating: -1 }
}
] )

上述管道:

  • 使用 $match过滤在 2002、2003 或 2004 上映且至少获得 5、000 IMDB 投票的动作片。

  • 使用 $setWindowFields 按 year 对电影进行分区。在每个分区中,$percentile操作符使用 p: [0.9] 和存储在 top10PctRatingForYear 中的无界窗口计算第 90百分位数IMDB 评级。

  • 使用 $match 和 $expr过滤IMDB 评分大于或等于当年第 90百分位数评分的电影。

  • 使用 $project 在输出中包含 title、year、imdb_rating 和 top10PctRatingForYear 字段。

  • 使用 $sort 按年份升序排列结果,然后按 IMDB 评分降序排列。

给本页内容打分