

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# $median
<a name="median"></a>

8.0.1 版的新功能。

Amazon DocumentDB 中的`$median`運算子會計算數值資料的中位數值。作為累積器，它會計算彙總管道`$group`階段中群組內文件的數值中位數。做為表達式，它會計算數字陣列的中位數。

**參數**
+ `input`：解析為數值或數值陣列的表達式。
+ `method`：指定計算方法的字串。目前僅`"approximate"`支援使用 t-digest 演算法的 。

## Behavior (行為)
<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()
```

------