本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
8.0.1 版中的新增内容。
Amazon DocumentDB 中的$median运算符计算数字数据的中值。作为累加器,它计算聚合管道$group阶段组内文档中数值的中位数。作为表达式,它计算数字数组的中位数。
参数
该"approximate"方法使用 t-digest 算法来计算近似中位数。结果是数据集中的现有值,而不是值之间的插值。随着数据点数量的增加,精度也会提高。
以下示例显示如何使用$median运算符计算每个类别的测试分数中位数。
创建示例文档
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",
medianScore: { $median: { input: "$score", method: "approximate" } }
}}
]);
输出
[
{ "_id": "A", "medianScore": 85 },
{ "_id": "B", "medianScore": 80 }
]
该$median运算符也可以用作$project阶段内的表达式来计算数组字段的中位数。
创建示例文档
db.surveys.insertMany([
{ _id: 1, ratings: [3, 5, 7, 9, 2] },
{ _id: 2, ratings: [10, 20, 30, 40, 50] },
{ _id: 3, ratings: [1, 1, 2, 3, 5] }
]);
查询示例
db.surveys.aggregate([
{ $project: {
medianRating: { $median: { input: "$ratings", method: "approximate" } }
}}
]);
输出
[
{ "_id": 1, "medianRating": 5 },
{ "_id": 2, "medianRating": 30 },
{ "_id": 3, "medianRating": 2 }
]
8.0.2 版中的新内容。
该$median操作员还可以在$setWindowFields舞台中用作窗口操作员。在这种情况下,它计算每个窗口中文档数值的中位数。您可以在output字段下指定运算符,也可以选择使用window文档定义窗口边界。
在中用作窗口运算符时$setWindowFields,中间数据限制$median为 100 MB。超过此限制的操作会返回错误。
创建示例文档
db.temperatures.insertMany([
{ _id: 1, city: "A", reading: 60 },
{ _id: 2, city: "A", reading: 65 },
{ _id: 3, city: "A", reading: 70 },
{ _id: 4, city: "B", reading: 80 },
{ _id: 5, city: "B", reading: 85 },
{ _id: 6, city: "B", reading: 90 }
]);
查询示例
以下示例按分区对文档进行分区,city并计算每个分区中reading所有文档的中位数。
db.temperatures.aggregate([
{
$setWindowFields: {
partitionBy: "$city",
output: {
medianReading: {
$median: { input: "$reading", method: "approximate" },
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]);
输出
[
{ "_id": 1, "city": "A", "reading": 60, "medianReading": 65 },
{ "_id": 2, "city": "A", "reading": 65, "medianReading": 65 },
{ "_id": 3, "city": "A", "reading": 70, "medianReading": 65 },
{ "_id": 4, "city": "B", "reading": 80, "medianReading": 85 },
{ "_id": 5, "city": "B", "reading": 85, "medianReading": 85 },
{ "_id": 6, "city": "B", "reading": 90, "medianReading": 85 }
]
每个文档都使用medianReading其分区中reading所有文档的近似中位数进行增强。
要查看使用$median运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示累加器的用法 (in$group)、表达式的用法 (in$project) 和窗口运算符的用法 (in$setWindowFields):
- 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: median across grouped documents
const students = db.collection('students');
await 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 }
]);
const accumulatorResult = await students.aggregate([
{ $group: {
_id: "$class",
medianScore: { $median: { input: "$score", method: "approximate" } }
}}
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Expression usage: median of an array field
const surveys = db.collection('surveys');
await surveys.insertMany([
{ _id: 1, ratings: [3, 5, 7, 9, 2] },
{ _id: 2, ratings: [10, 20, 30, 40, 50] },
{ _id: 3, ratings: [1, 1, 2, 3, 5] }
]);
const expressionResult = await surveys.aggregate([
{ $project: {
medianRating: { $median: { input: "$ratings", method: "approximate" } }
}}
]).toArray();
console.log('Expression result:', expressionResult);
// Window operator usage: median across each partition
const temperatures = db.collection('temperatures');
await temperatures.insertMany([
{ _id: 1, city: "A", reading: 60 },
{ _id: 2, city: "A", reading: 65 },
{ _id: 3, city: "A", reading: 70 },
{ _id: 4, city: "B", reading: 80 },
{ _id: 5, city: "B", reading: 85 },
{ _id: 6, city: "B", reading: 90 }
]);
const windowResult = await temperatures.aggregate([
{
$setWindowFields: {
partitionBy: "$city",
output: {
medianReading: {
$median: { input: "$reading", method: "approximate" },
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
} 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: median across grouped documents
students = db['students']
students.insert_many([
{ '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 }
])
accumulator_result = list(students.aggregate([
{ '$group': {
'_id': '$class',
'medianScore': { '$median': { 'input': '$score', 'method': 'approximate' } }
}}
]))
print('Accumulator result:', accumulator_result)
# Expression usage: median of an array field
surveys = db['surveys']
surveys.insert_many([
{ '_id': 1, 'ratings': [3, 5, 7, 9, 2] },
{ '_id': 2, 'ratings': [10, 20, 30, 40, 50] },
{ '_id': 3, 'ratings': [1, 1, 2, 3, 5] }
])
expression_result = list(surveys.aggregate([
{ '$project': {
'medianRating': { '$median': { 'input': '$ratings', 'method': 'approximate' } }
}}
]))
print('Expression result:', expression_result)
# Window operator usage: median across each partition
temperatures = db['temperatures']
temperatures.insert_many([
{ '_id': 1, 'city': 'A', 'reading': 60 },
{ '_id': 2, 'city': 'A', 'reading': 65 },
{ '_id': 3, 'city': 'A', 'reading': 70 },
{ '_id': 4, 'city': 'B', 'reading': 80 },
{ '_id': 5, 'city': 'B', 'reading': 85 },
{ '_id': 6, 'city': 'B', 'reading': 90 }
])
window_result = list(temperatures.aggregate([
{
'$setWindowFields': {
'partitionBy': '$city',
'output': {
'medianReading': {
'$median': { 'input': '$reading', 'method': 'approximate' },
'window': { 'documents': ['unbounded', 'unbounded'] }
}
}
}
}
]))
print('Window result:', window_result)
finally:
client.close()
example()