View a markdown version of this page

$standard DevPop - 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à.

$standard DevPop

Nuovo dalla versione 8.0.1.

L'$stdDevPopoperatore in Amazon DocumentDB calcola la deviazione standard dei valori numerici della popolazione. Come accumulatore, calcola la deviazione standard della popolazione tra i documenti all'interno di un gruppo nella fase di una pipeline di aggregazione. $group Come espressione, calcola la deviazione standard della popolazione di una serie di numeri. La deviazione standard della popolazione utilizza N come divisore (non). N-1 Non-numeric i valori vengono ignorati. Se non sono presenti valori numerici, viene restituito. null Se è presente un solo valore numerico, viene restituito. 0

Parametri

  • expression: un'espressione che si risolve in un valore numerico o in una matrice di valori numerici.

Esempio (MongoDB Shell)

L'esempio seguente mostra come utilizzare l'$stdDevPopoperatore per calcolare la deviazione standard della popolazione dei punteggi per soggetto.

Crea documenti di esempio

db.scores.insertMany([ { subject: "math", score: 60 }, { subject: "math", score: 75 }, { subject: "math", score: 85 }, { subject: "math", score: 92 }, { subject: "math", score: 78 }, { subject: "science", score: 55 }, { subject: "science", score: 70 }, { subject: "science", score: 82 }, { subject: "science", score: 91 }, { subject: "science", score: 67 } ]);

Esempio di interrogazione

db.scores.aggregate([ { $group: { _id: "$subject", stdDev: { $stdDevPop: "$score" } }} ]);

Output

[ { "_id": "math", "stdDev": 10.75174404457249 }, { "_id": "science", "stdDev": 12.441864811996632 } ]

Esempio di utilizzo delle espressioni (MongoDB Shell)

L'$stdDevPopoperatore può essere utilizzato anche come espressione all'interno di uno $project stadio per calcolare la deviazione standard della popolazione di un campo di matrice.

Crea documenti di esempio

db.experiments.insertMany([ { _id: 1, measurements: [10, 12, 14, 16, 18] }, { _id: 2, measurements: [5, 5, 5, 5, 5] }, { _id: 3, measurements: [2, 4, 6, 8, 10] } ]);

Esempio di interrogazione

db.experiments.aggregate([ { $project: { stdDev: { $stdDevPop: "$measurements" } }} ]);

Output

[ { "_id": 1, "stdDev": 2.8284271247461903 }, { "_id": 2, "stdDev": 0 }, { "_id": 3, "stdDev": 2.8284271247461903 } ]

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

Nuovo dalla versione 8.0.2.

L'$stdDevPopoperatore può essere utilizzato anche come operatore di finestra nello $setWindowFields stage. In questo contesto, restituisce la deviazione standard della popolazione dell'espressione specificata per i documenti in ciascuna 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.sensorData.insertMany([ { _id: 1, sensor: "A", time: 1, reading: 4 }, { _id: 2, sensor: "A", time: 2, reading: 10 }, { _id: 3, sensor: "A", time: 3, reading: 10 }, { _id: 4, sensor: "B", time: 1, reading: 10 }, { _id: 5, sensor: "B", time: 2, reading: 20 } ]);

Esempio di interrogazione

L'esempio seguente partiziona i documenti in basesensor, ordina ogni partizione in base time e restituisce la deviazione standard della popolazione corrente reading compresa tra l'inizio della partizione e il documento corrente.

db.sensorData.aggregate([ { $setWindowFields: { partitionBy: "$sensor", sortBy: { time: 1 }, output: { runningStdDev: { $stdDevPop: "$reading", window: { documents: ["unbounded", "current"] } } } } } ]);

Output

[ { "_id": 1, "sensor": "A", "time": 1, "reading": 4, "runningStdDev": 0 }, { "_id": 2, "sensor": "A", "time": 2, "reading": 10, "runningStdDev": 3 }, { "_id": 3, "sensor": "A", "time": 3, "reading": 10, "runningStdDev": 2.8284271247461903 }, { "_id": 4, "sensor": "B", "time": 1, "reading": 10, "runningStdDev": 0 }, { "_id": 5, "sensor": "B", "time": 2, "reading": 20, "runningStdDev": 5 } ]

Ogni documento è arricchito con runningStdDev la deviazione standard della popolazione reading all'interno della sua partizione fino al documento corrente incluso. Quando la finestra contiene un singolo valore, restituisce. $stdDevPop 0

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo $stdDevPop dell'operatore, scegliete la scheda corrispondente alla lingua che desiderate utilizzare. Gli esempi seguenti mostrano l'uso dell'accumulatore (in$group), l'uso delle espressioni (in$project) e l'uso dell'operatore di finestra (in$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: stdDevPop across grouped documents const scores = db.collection('scores'); await scores.insertMany([ { subject: "math", score: 60 }, { subject: "math", score: 75 }, { subject: "math", score: 85 }, { subject: "math", score: 92 }, { subject: "math", score: 78 }, { subject: "science", score: 55 }, { subject: "science", score: 70 }, { subject: "science", score: 82 }, { subject: "science", score: 91 }, { subject: "science", score: 67 } ]); const accumulatorResult = await scores.aggregate([ { $group: { _id: "$subject", stdDev: { $stdDevPop: "$score" } }} ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: stdDevPop of an array field const experiments = db.collection('experiments'); await experiments.insertMany([ { _id: 1, measurements: [10, 12, 14, 16, 18] }, { _id: 2, measurements: [5, 5, 5, 5, 5] }, { _id: 3, measurements: [2, 4, 6, 8, 10] } ]); const expressionResult = await experiments.aggregate([ { $project: { stdDev: { $stdDevPop: "$measurements" } }} ]).toArray(); console.log('Expression result:', expressionResult); // Window operator usage: running stdDevPop within each partition const sensorData = db.collection('sensorData'); await sensorData.insertMany([ { _id: 1, sensor: "A", time: 1, reading: 4 }, { _id: 2, sensor: "A", time: 2, reading: 10 }, { _id: 3, sensor: "A", time: 3, reading: 10 }, { _id: 4, sensor: "B", time: 1, reading: 10 }, { _id: 5, sensor: "B", time: 2, reading: 20 } ]); const windowResult = await sensorData.aggregate([ { $setWindowFields: { partitionBy: "$sensor", sortBy: { time: 1 }, output: { runningStdDev: { $stdDevPop: "$reading", window: { documents: ["unbounded", "current"] } } } } } ]).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: stdDevPop across grouped documents scores = db['scores'] scores.insert_many([ { 'subject': 'math', 'score': 60 }, { 'subject': 'math', 'score': 75 }, { 'subject': 'math', 'score': 85 }, { 'subject': 'math', 'score': 92 }, { 'subject': 'math', 'score': 78 }, { 'subject': 'science', 'score': 55 }, { 'subject': 'science', 'score': 70 }, { 'subject': 'science', 'score': 82 }, { 'subject': 'science', 'score': 91 }, { 'subject': 'science', 'score': 67 } ]) accumulator_result = list(scores.aggregate([ { '$group': { '_id': '$subject', 'stdDev': { '$stdDevPop': '$score' } }} ])) print('Accumulator result:', accumulator_result) # Expression usage: stdDevPop of an array field experiments = db['experiments'] experiments.insert_many([ { '_id': 1, 'measurements': [10, 12, 14, 16, 18] }, { '_id': 2, 'measurements': [5, 5, 5, 5, 5] }, { '_id': 3, 'measurements': [2, 4, 6, 8, 10] } ]) expression_result = list(experiments.aggregate([ { '$project': { 'stdDev': { '$stdDevPop': '$measurements' } }} ])) print('Expression result:', expression_result) # Window operator usage: running stdDevPop within each partition sensor_data = db['sensorData'] sensor_data.insert_many([ { '_id': 1, 'sensor': 'A', 'time': 1, 'reading': 4 }, { '_id': 2, 'sensor': 'A', 'time': 2, 'reading': 10 }, { '_id': 3, 'sensor': 'A', 'time': 3, 'reading': 10 }, { '_id': 4, 'sensor': 'B', 'time': 1, 'reading': 10 }, { '_id': 5, 'sensor': 'B', 'time': 2, 'reading': 20 } ]) window_result = list(sensor_data.aggregate([ { '$setWindowFields': { 'partitionBy': '$sensor', 'sortBy': { 'time': 1 }, 'output': { 'runningStdDev': { '$stdDevPop': '$reading', 'window': { 'documents': ['unbounded', 'current'] } } } } } ])) print('Window result:', window_result) finally: client.close() example()