翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$avg
Amazon DocumentDB の$avg集計演算子は、ステージに入力されるドキュメント全体で指定された式の平均値を計算します。この演算子は、一連のドキュメントにわたる数値フィールドまたは式の平均を計算するのに役立ちます。
パラメータ
例 (MongoDB シェル)
次の例は、 $avg演算子を使用して、一連の学生ドキュメントの平均スコアを計算する方法を示しています。
サンプルドキュメントを作成する
db.students.insertMany([
{ name: "John", score: 85 },
{ name: "Jane", score: 92 },
{ name: "Bob", score: 78 },
{ name: "Alice", score: 90 }
]);
クエリの例
db.students.aggregate([
{ $group: {
_id: null,
avgScore: { $avg: "$score" }
}}
]);
出力
[
{
"_id": null,
"avgScore": 86.25
}
]
ウィンドウ演算子の使用例 (MongoDB シェル)
バージョン 8.0.2 の新機能。
$avg 演算子は、$setWindowFieldsステージのウィンドウ演算子としても使用できます。このコンテキストでは、各ウィンドウのドキュメントに対して指定された式の平均を返します。output フィールドで 演算子を指定し、オプションでwindowドキュメントを使用してウィンドウの境界を定義します。
サンプルドキュメントを作成する
db.readings.insertMany([
{ _id: 1, city: "Denver", day: 1, temp: 70 },
{ _id: 2, city: "Denver", day: 2, temp: 80 },
{ _id: 3, city: "Seattle", day: 1, temp: 60 },
{ _id: 4, city: "Seattle", day: 2, temp: 64 },
{ _id: 5, city: "Seattle", day: 3, temp: 68 }
]);
クエリの例
次の例では、ドキュメントを でパーティション化しcity、各パーティションを でソートしてday、パーティションの開始tempから現在のドキュメントまでの の実行平均を返します。
db.readings.aggregate([
{
$setWindowFields: {
partitionBy: "$city",
sortBy: { day: 1 },
output: {
runningAvg: {
$avg: "$temp",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
出力
[
{ "_id": 1, "city": "Denver", "day": 1, "temp": 70, "runningAvg": 70 },
{ "_id": 2, "city": "Denver", "day": 2, "temp": 80, "runningAvg": 75 },
{ "_id": 3, "city": "Seattle", "day": 1, "temp": 60, "runningAvg": 60 },
{ "_id": 4, "city": "Seattle", "day": 2, "temp": 64, "runningAvg": 62 },
{ "_id": 5, "city": "Seattle", "day": 3, "temp": 68, "runningAvg": 64 }
]
各ドキュメントはrunningAvg、現在のドキュメントまでのパーティションtemp内の の平均である で拡張されます。
コードの例
$avg 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。次の例は、アキュムレータの使用 ( の場合$group) とウィンドウ演算子の使用 ( の場合) の両方を示しています$setWindowFields。
- Node.js
-
const { MongoClient } = require('mongodb');
async function calculateAvgScore() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
// Accumulator usage: average across grouped documents
const students = db.collection('students');
await students.insertMany([
{ name: "John", score: 85 },
{ name: "Jane", score: 92 },
{ name: "Bob", score: 78 },
{ name: "Alice", score: 90 }
]);
const accumulatorResult = await students.aggregate([
{ $group: {
_id: null,
avgScore: { $avg: '$score' }
}}
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: running average within each partition
const readings = db.collection('readings');
await readings.insertMany([
{ _id: 1, city: "Denver", day: 1, temp: 70 },
{ _id: 2, city: "Denver", day: 2, temp: 80 },
{ _id: 3, city: "Seattle", day: 1, temp: 60 },
{ _id: 4, city: "Seattle", day: 2, temp: 64 },
{ _id: 5, city: "Seattle", day: 3, temp: 68 }
]);
const windowResult = await readings.aggregate([
{
$setWindowFields: {
partitionBy: "$city",
sortBy: { day: 1 },
output: {
runningAvg: {
$avg: "$temp",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
await client.close();
}
calculateAvgScore();
- Python
-
from pymongo import MongoClient
def calculate_avg_score():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client.test
# Accumulator usage: average across grouped documents
students = db.students
students.insert_many([
{ 'name': 'John', 'score': 85 },
{ 'name': 'Jane', 'score': 92 },
{ 'name': 'Bob', 'score': 78 },
{ 'name': 'Alice', 'score': 90 }
])
accumulator_result = list(students.aggregate([
{ '$group': {
'_id': None,
'avgScore': { '$avg': '$score' }
}}
]))
print('Accumulator result:', accumulator_result)
# Window operator usage: running average within each partition
readings = db.readings
readings.insert_many([
{ '_id': 1, 'city': 'Denver', 'day': 1, 'temp': 70 },
{ '_id': 2, 'city': 'Denver', 'day': 2, 'temp': 80 },
{ '_id': 3, 'city': 'Seattle', 'day': 1, 'temp': 60 },
{ '_id': 4, 'city': 'Seattle', 'day': 2, 'temp': 64 },
{ '_id': 5, 'city': 'Seattle', 'day': 3, 'temp': 68 }
])
window_result = list(readings.aggregate([
{
'$setWindowFields': {
'partitionBy': '$city',
'sortBy': { 'day': 1 },
'output': {
'runningAvg': {
'$avg': '$temp',
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
print('Window result:', window_result)
client.close()
calculate_avg_score()