本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$avg
Amazon DocumentDB $avg 中的彙總運算子會計算輸入階段的文件中指定表達式的平均值。此運算子有助於計算一組文件間數值欄位或表達式的平均值。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $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 Shell)
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()