View a markdown version of this page

$avg - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$avg

Amazon DocumentDB 中的$avg聚合运算符计算输入到该阶段的文档中指定表达式的平均值。此运算符可用于计算一组文档中数值字段或表达式的平均值。

参数

  • expression:用于计算平均值的表达式。这可以是字段路径(例如"$field")或表达式(例如{ $multiply: ["$field1", "$field2"] })。

示例(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()