翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
バージョン 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()