本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$stdDevPop
8.0.1 版的新功能。
Amazon DocumentDB 中的$stdDevPop運算子會計算數值的母群體標準差。作為累積器,它會計算彙總管道$group階段中群組內文件的母體標準差。做為表達式,它會計算數字陣列的母體標準差。母群體標準差使用 N 作為除數 (而非 N-1)。會忽略非數值。如果沒有數值,則會傳回 null。如果只有一個數值,則會傳回 0。
參數
範例 (MongoDB Shell)
下列範例顯示如何使用 $stdDevPop 運算子計算每個主體的母群體分數標準差。
建立範例文件
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 }
]);
查詢範例
db.scores.aggregate([
{ $group: {
_id: "$subject",
stdDev: { $stdDevPop: "$score" }
}}
]);
輸出
[
{ "_id": "math", "stdDev": 10.75174404457249 },
{ "_id": "science", "stdDev": 12.441864811996632 }
]
表達式用量範例 (MongoDB Shell)
運算$stdDevPop子也可以用作$project階段內的表達式,以計算陣列欄位的母群體標準差。
建立範例文件
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] }
]);
查詢範例
db.experiments.aggregate([
{ $project: {
stdDev: { $stdDevPop: "$measurements" }
}}
]);
輸出
[
{ "_id": 1, "stdDev": 2.8284271247461903 },
{ "_id": 2, "stdDev": 0 },
{ "_id": 3, "stdDev": 2.8284271247461903 }
]
視窗運算子用量範例 (MongoDB Shell)
8.0.2 版的新功能。
該$stdDevPop運算子也可以用作$setWindowFields階段中的視窗運算子。在這種情況下,它會傳回每個視窗中文件指定表達式的母群體標準差。您可以在 output 欄位下指定運算子,並選擇性地使用window文件定義視窗邊界。
建立範例文件
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 }
]);
查詢範例
下列範例會依 分割文件sensor、依 排序每個分割區time,並傳回reading從分割區開頭到目前文件的執行中母體標準差 。
db.sensorData.aggregate([
{
$setWindowFields: {
partitionBy: "$sensor",
sortBy: { time: 1 },
output: {
runningStdDev: {
$stdDevPop: "$reading",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
輸出
[
{ "_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 }
]
每個文件都會擴增為 runningStdDev,也就是其分割區reading內直到並包含目前文件的母群體標準差。當視窗包含單一值時, $stdDevPop會傳回 0。
程式碼範例
若要檢視使用 $stdDevPop 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group)、表達式用量 (在 中$project) 和視窗運算子用量 (在 中$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()