

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# $median
<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 쉘)
<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()
```

------