View a markdown version of this page

$avg - Amazon DocumentDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

$avg

L'operatore di $avg aggregazione in Amazon DocumentDB calcola il valore medio dell'espressione specificata tra i documenti che vengono inseriti nello stage. Questo operatore è utile per calcolare la media di un campo numerico o di un'espressione in un set di documenti.

Parametri

  • expression: L'espressione da utilizzare per calcolare la media. Può essere un percorso di campo (ad es."$field") o un'espressione (ad es.{ $multiply: ["$field1", "$field2"] }).

Esempio (MongoDB Shell)

L'esempio seguente dimostra come utilizzare l'$avgoperatore per calcolare il punteggio medio in una serie di documenti degli studenti.

Crea documenti di esempio

db.students.insertMany([ { name: "John", score: 85 }, { name: "Jane", score: 92 }, { name: "Bob", score: 78 }, { name: "Alice", score: 90 } ]);

Esempio di interrogazione

db.students.aggregate([ { $group: { _id: null, avgScore: { $avg: "$score" } }} ]);

Output

[ { "_id": null, "avgScore": 86.25 } ]

Esempio di utilizzo dell'operatore di finestra (MongoDB Shell)

Nuovo dalla versione 8.0.2.

L'$avgoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce la media dell'espressione specificata per i documenti in ogni finestra. Si specifica l'operatore sotto il output campo e, facoltativamente, si definiscono i confini della finestra con un window documento.

Create documenti di esempio

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 } ]);

Esempio di interrogazione

L'esempio seguente suddivide i documenti in basecity, ordina ogni partizione in base day e restituisce una media corrente del valore temp compreso tra l'inizio della partizione e il documento corrente.

db.readings.aggregate([ { $setWindowFields: { partitionBy: "$city", sortBy: { day: 1 }, output: { runningAvg: { $avg: "$temp", window: { documents: ["unbounded", "current"] } } } } } ]);

Output

[ { "_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 } ]

Ogni documento è runningAvg arricchito dalla media dei contenuti temp all'interno della partizione fino al documento corrente incluso.

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo $avg dell'operatore, scegli la scheda corrispondente alla lingua che desideri utilizzare. Gli esempi seguenti mostrano sia l'utilizzo dell'accumulatore (in$group) che l'utilizzo dell'operatore di finestra (in$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()