

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

# $std DevPop
<a name="stdDevPop"></a>

8.0.1 版中的新增内容。

Amazon DocumentDB 中的`$stdDevPop`运算符计算数值的总体标准差。作为累加器，它计算聚合管道`$group`阶段组内文档的总体标准差。作为表达式，它计算数字数组的总体标准差。总体标准差使用 N 作为除数（不是 N-1）。 Non-numeric 值被忽略。如果没有数值，则返回`null`。如果只有一个数值，则返回`0`。

**参数**
+ `expression`：解析为数值或数值数组的表达式。

## 示例（MongoDB Shell）
<a name="stdDevPop-examples"></a>

以下示例说明如何使用`$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）
<a name="stdDevPop-expression-examples"></a>

该`$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 }
]
```

## 代码示例
<a name="stdDevPop-code"></a>

要查看使用`$stdDevPop`运算符的代码示例，请选择要使用的语言的选项卡。以下示例显示了累加器的用法（输入`$group`）和表达式用法（中`$project`）：

------
#### [ 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');
    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');
    const expressionResult = await experiments.aggregate([
      { $project: {
          stdDev: { $stdDevPop: "$measurements" }
        }}
    ]).toArray();
    console.log('Expression result:', expressionResult);

  } 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']
        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']
        expression_result = list(experiments.aggregate([
            { '$project': {
                'stdDev': { '$stdDevPop': '$measurements' }
            }}
        ]))
        print('Expression result:', expression_result)

    finally:
        client.close()

example()
```

------