

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

# $中位数
<a name="median"></a>

8.0.1 版中的新增内容。

Amazon DocumentDB 中的`$median`运算符计算数字数据的中值。作为累加器，它计算聚合管道`$group`阶段组内文档中数值的中位数。作为表达式，它计算数字数组的中位数。

**参数**
+ `input`：解析为数值或数值数组的表达式。
+ `method`：一个指定计算方法的字符串。目前`"approximate"`仅支持使用 t-digest 算法。

## 行为
<a name="median-behavior"></a>

该`"approximate"`方法使用 t-digest 算法来计算近似中位数。结果是数据集中的现有值，而不是值之间的插值。随着数据点数量的增加，精度也会提高。

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

以下示例显示如何使用`$median`运算符计算每个类别的测试分数中位数。

**创建示例文档 **

```
db.students.insertMany([
  { class: "A", score: 72 },
  { class: "A", score: 85 },
  { class: "A", score: 90 },
  { class: "A", score: 68 },
  { class: "A", score: 95 },
  { class: "B", score: 80 },
  { class: "B", score: 75 },
  { class: "B", score: 92 },
  { class: "B", score: 88 },
  { class: "B", score: 70 }
]);
```

**查询示例 **

```
db.students.aggregate([
  { $group: {
      _id: "$class",
      medianScore: { $median: { input: "$score", method: "approximate" } }
    }}
]);
```

**输出**

```
[
  { "_id": "A", "medianScore": 85 },
  { "_id": "B", "medianScore": 80 }
]
```

## 表达式用法示例（MongoDB Shell）
<a name="median-expression-examples"></a>

该`$median`运算符也可以用作`$project`阶段内的表达式来计算数组字段的中位数。

**创建示例文档 **

```
db.surveys.insertMany([
  { _id: 1, ratings: [3, 5, 7, 9, 2] },
  { _id: 2, ratings: [10, 20, 30, 40, 50] },
  { _id: 3, ratings: [1, 1, 2, 3, 5] }
]);
```

**查询示例 **

```
db.surveys.aggregate([
  { $project: {
      medianRating: { $median: { input: "$ratings", method: "approximate" } }
    }}
]);
```

**输出**

```
[
  { "_id": 1, "medianRating": 5 },
  { "_id": 2, "medianRating": 30 },
  { "_id": 3, "medianRating": 2 }
]
```

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

要查看使用`$median`运算符的代码示例，请选择要使用的语言的选项卡。以下示例显示了累加器的用法（输入`$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: median across grouped documents
    const students = db.collection('students');
    const accumulatorResult = await students.aggregate([
      { $group: {
          _id: "$class",
          medianScore: { $median: { input: "$score", method: "approximate" } }
        }}
    ]).toArray();
    console.log('Accumulator result:', accumulatorResult);

    // Expression usage: median of an array field
    const surveys = db.collection('surveys');
    const expressionResult = await surveys.aggregate([
      { $project: {
          medianRating: { $median: { input: "$ratings", method: "approximate" } }
        }}
    ]).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: median across grouped documents
        students = db['students']
        accumulator_result = list(students.aggregate([
            { '$group': {
                '_id': '$class',
                'medianScore': { '$median': { 'input': '$score', 'method': 'approximate' } }
            }}
        ]))
        print('Accumulator result:', accumulator_result)

        # Expression usage: median of an array field
        surveys = db['surveys']
        expression_result = list(surveys.aggregate([
            { '$project': {
                'medianRating': { '$median': { 'input': '$ratings', 'method': 'approximate' } }
            }}
        ]))
        print('Expression result:', expression_result)

    finally:
        client.close()

example()
```

------