本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$std DevSamp
8.0.1 版中的新增内容。
Amazon DocumentDB 中的$stdDevSamp运算符计算数值的样本标准差。作为累加器,它计算聚合管道$group阶段中组内文档的样本标准差。作为表达式,它计算数字数组的样本标准差。样本标准差用 N-1 作除数(贝塞尔校正)。 Non-numeric 值被忽略。如果数值少于两个数值,则返回null。
参数
示例(MongoDB Shell)
以下示例显示如何使用$stdDevSamp运算符计算每个受试者分数的样本标准差。
创建示例文档
db.scores.insertMany([
{ subject: "math", score: 80 },
{ subject: "math", score: 90 },
{ subject: "math", score: 85 },
{ subject: "math", score: 95 },
{ subject: "science", score: 70 },
{ subject: "science", score: 75 },
{ subject: "science", score: 80 },
{ subject: "science", score: 85 }
]);
查询示例
db.scores.aggregate([
{ $group: {
_id: "$subject",
stdDev: { $stdDevSamp: "$score" }
}}
]);
输出
[
{ "_id": "math", "stdDev": 6.454972243679028 },
{ "_id": "science", "stdDev": 6.454972243679028 }
]
表达式用法示例(MongoDB Shell)
该$stdDevSamp运算符还可用作$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: { $stdDevSamp: "$measurements" }
}}
]);
输出
[
{ "_id": 1, "stdDev": 3.1622776601683795 },
{ "_id": 2, "stdDev": 0 },
{ "_id": 3, "stdDev": 3.1622776601683795 }
]
窗口运算符用法示例(MongoDB Shell)
8.0.2 版中的新内容。
该$stdDevSamp操作员还可以在$setWindowFields舞台中用作窗口操作员。在这种情况下,它返回每个窗口中文档的指定表达式的样本标准差。您可以在output字段下指定运算符,也可以选择使用window文档定义窗口边界。
创建示例文档
db.sensorReadings.insertMany([
{ _id: 1, sensor: "A", time: 1, value: 2 },
{ _id: 2, sensor: "A", time: 2, value: 4 },
{ _id: 3, sensor: "A", time: 3, value: 6 },
{ _id: 4, sensor: "B", time: 1, value: 10 },
{ _id: 5, sensor: "B", time: 2, value: 12 }
]);
查询示例
以下示例按文档分区sensor,按分区排序time,并返回value从分区起点到当前文档的运行样本标准差。
db.sensorReadings.aggregate([
{
$setWindowFields: {
partitionBy: "$sensor",
sortBy: { time: 1 },
output: {
runningStdDev: {
$stdDevSamp: "$value",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
输出
[
{ "_id": 1, "sensor": "A", "time": 1, "value": 2, "runningStdDev": null },
{ "_id": 2, "sensor": "A", "time": 2, "value": 4, "runningStdDev": 1.4142135623730951 },
{ "_id": 3, "sensor": "A", "time": 3, "value": 6, "runningStdDev": 2 },
{ "_id": 4, "sensor": "B", "time": 1, "value": 10, "runningStdDev": null },
{ "_id": 5, "sensor": "B", "time": 2, "value": 12, "runningStdDev": 1.4142135623730951 }
]
每个文档都添加runningStdDev了其分区value内直到包括当前文档在内的样本标准差。当窗口包含少于两个值(每个分区中的第一个文档)时,$stdDevSamp返回null。
代码示例
要查看使用$stdDevSamp运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示累加器的用法 (in$group)、表达式的用法 (in$project) 和窗口运算符的用法 (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: stdDevSamp across grouped documents
const scores = db.collection('scores');
await scores.insertMany([
{ subject: "math", score: 80 },
{ subject: "math", score: 90 },
{ subject: "math", score: 85 },
{ subject: "math", score: 95 },
{ subject: "science", score: 70 },
{ subject: "science", score: 75 },
{ subject: "science", score: 80 },
{ subject: "science", score: 85 }
]);
const accumulatorResult = await scores.aggregate([
{ $group: {
_id: "$subject",
stdDev: { $stdDevSamp: "$score" }
}}
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Expression usage: stdDevSamp 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: { $stdDevSamp: "$measurements" }
}}
]).toArray();
console.log('Expression result:', expressionResult);
// Window operator usage: running stdDevSamp within each partition
const sensorReadings = db.collection('sensorReadings');
await sensorReadings.insertMany([
{ _id: 1, sensor: "A", time: 1, value: 2 },
{ _id: 2, sensor: "A", time: 2, value: 4 },
{ _id: 3, sensor: "A", time: 3, value: 6 },
{ _id: 4, sensor: "B", time: 1, value: 10 },
{ _id: 5, sensor: "B", time: 2, value: 12 }
]);
const windowResult = await sensorReadings.aggregate([
{
$setWindowFields: {
partitionBy: "$sensor",
sortBy: { time: 1 },
output: {
runningStdDev: {
$stdDevSamp: "$value",
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: stdDevSamp across grouped documents
scores = db['scores']
scores.insert_many([
{ 'subject': 'math', 'score': 80 },
{ 'subject': 'math', 'score': 90 },
{ 'subject': 'math', 'score': 85 },
{ 'subject': 'math', 'score': 95 },
{ 'subject': 'science', 'score': 70 },
{ 'subject': 'science', 'score': 75 },
{ 'subject': 'science', 'score': 80 },
{ 'subject': 'science', 'score': 85 }
])
accumulator_result = list(scores.aggregate([
{ '$group': {
'_id': '$subject',
'stdDev': { '$stdDevSamp': '$score' }
}}
]))
print('Accumulator result:', accumulator_result)
# Expression usage: stdDevSamp 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': { '$stdDevSamp': '$measurements' }
}}
]))
print('Expression result:', expression_result)
# Window operator usage: running stdDevSamp within each partition
sensor_readings = db['sensorReadings']
sensor_readings.insert_many([
{ '_id': 1, 'sensor': 'A', 'time': 1, 'value': 2 },
{ '_id': 2, 'sensor': 'A', 'time': 2, 'value': 4 },
{ '_id': 3, 'sensor': 'A', 'time': 3, 'value': 6 },
{ '_id': 4, 'sensor': 'B', 'time': 1, 'value': 10 },
{ '_id': 5, 'sensor': 'B', 'time': 2, 'value': 12 }
])
window_result = list(sensor_readings.aggregate([
{
'$setWindowFields': {
'partitionBy': '$sensor',
'sortBy': { 'time': 1 },
'output': {
'runningStdDev': {
'$stdDevSamp': '$value',
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
print('Window result:', window_result)
finally:
client.close()
example()