本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$百分位数
8.0.1 版中的新增内容。
Amazon DocumentDB 中的$percentile运算符为数字数据计算指定的百分位值。作为累加器,它在聚合管道$group阶段计算组内文档的百分位数值。作为表达式,它计算数字数组的百分位数。
参数
-
input:解析为数值或数值数组的表达式。
-
p:介于 0 和 1 之间的百分位数值的数组,其中每个值代表要计算的百分位数。例如,[0.25, 0.5, 0.75]计算第 25、50 和 75 个百分位数。
-
method:一个指定计算方法的字符串。目前仅支持 "approximate"。
行为
该"approximate"方法使用 t-digest 算法来计算基于百分位数的近似指标。对于小型数据集,不同的百分位数值可能会解析为相同的结果。例如,如果每组只有 5 个值,则 p90 和 p99 都可能返回该组中的最大值。随着数据点数量的增加,精度也会提高。
示例(MongoDB Shell)
以下示例说明如何使用$percentile运算符计算每个班级分数的第 25 和第 75 个百分位数。
创建示例文档
db.students.insertMany([
{ class: "A", score: 72 },
{ class: "A", score: 85 },
{ class: "A", score: 90 },
{ class: "A", score: 68 },
{ class: "A", score: 95 },
{ class: "B", score: 80 },
{ class: "B", score: 75 },
{ class: "B", score: 92 },
{ class: "B", score: 88 },
{ class: "B", score: 70 }
]);
查询示例
db.students.aggregate([
{ $group: {
_id: "$class",
percentiles: { $percentile: { input: "$score", p: [0.25, 0.75], method: "approximate" } }
}}
]);
输出
[
{ "_id": "A", "percentiles": [72, 90] },
{ "_id": "B", "percentiles": [75, 88] }
]
表达式用法示例(MongoDB Shell)
该$percentile运算符还可用作$project阶段内的表达式来计算数组字段的百分位数。
创建示例文档
db.surveys.insertMany([
{ _id: 1, responses: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] },
{ _id: 2, responses: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] }
]);
查询示例
db.surveys.aggregate([
{ $project: {
quartiles: { $percentile: { input: "$responses", p: [0.25, 0.5, 0.75], method: "approximate" } }
}}
]);
输出
[
{ "_id": 1, "quartiles": [6, 10, 16] },
{ "_id": 2, "quartiles": [5, 9, 15] }
]
代码示例
要查看使用$percentile运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示了累加器的用法(输入$group)和表达式用法(中$project):
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db('test');
// Accumulator usage: percentiles across grouped documents
const students = db.collection('students');
const accumulatorResult = await students.aggregate([
{ $group: {
_id: "$class",
percentiles: { $percentile: { input: "$score", p: [0.25, 0.75], method: "approximate" } }
}}
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Expression usage: percentiles of an array field
const surveys = db.collection('surveys');
const expressionResult = await surveys.aggregate([
{ $project: {
quartiles: { $percentile: { input: "$responses", p: [0.25, 0.5, 0.75], method: "approximate" } }
}}
]).toArray();
console.log('Expression result:', expressionResult);
} finally {
await client.close();
}
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
try:
db = client['test']
# Accumulator usage: percentiles across grouped documents
students = db['students']
accumulator_result = list(students.aggregate([
{ '$group': {
'_id': '$class',
'percentiles': { '$percentile': { 'input': '$score', 'p': [0.25, 0.75], 'method': 'approximate' } }
}}
]))
print('Accumulator result:', accumulator_result)
# Expression usage: percentiles of an array field
surveys = db['surveys']
expression_result = list(surveys.aggregate([
{ '$project': {
'quartiles': { '$percentile': { 'input': '$responses', 'p': [0.25, 0.5, 0.75], 'method': 'approximate' } }
}}
]))
print('Expression result:', expression_result)
finally:
client.close()
example()