本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
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 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group)、表達式用量 (在 中$project) 和視窗運算子用量 (在 中$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()