

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

# $백분위수
<a name="percentile"></a>

버전 8.0.1에서 새로 추가되었습니다.

Amazon DocumentDB의 `$percentile` 연산자는 숫자 데이터에 대해 지정된 백분위수 값을 계산합니다. 누적기는 집계 파이프라인의 `$group` 단계에서 그룹 내 문서 전반의 백분위수 값을 계산합니다. 표현식으로 숫자 배열의 백분위수를 계산합니다.

**파라미터**
+ `input`: 숫자 값 또는 숫자 값 배열로 확인되는 표현식입니다.
+ `p`: 0에서 1 사이의 백분위수 값 배열로, 여기서 각 값은 계산할 백분위수를 나타냅니다. 예를 들어는 25번째, 50번째 및 75번째 백분위수를 `[0.25, 0.5, 0.75]` 계산합니다.
+ `method`: 계산 방법을 지정하는 문자열입니다. 현재 `"approximate"`만 지원됩니다.

## 동작
<a name="percentile-behavior"></a>

`"approximate"` 메서드는 t-digest 알고리즘을 사용하여 대략적인 백분위수 기반 지표를 계산합니다. 데이터 세트가 작으면 고유한 백분위수 값이 동일한 결과로 확인될 수 있습니다. 예를 들어 그룹당 값이 5개뿐인 경우 p90과 p99는 모두 그룹의 최대값을 반환할 수 있습니다. 데이터 포인트 수가 증가함에 따라 정밀도가 향상됩니다.

## 예제(MongoDB 쉘)
<a name="percentile-examples"></a>

다음 예제에서는 `$percentile` 연산자를 사용하여 클래스당 점수의 25번째 및 75번째 백분위수를 계산하는 방법을 보여줍니다.

**샘플 문서 생성**

```
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",
      percentiles: { $percentile: { input: "$score", p: [0.25, 0.75], method: "approximate" } }
    }}
]);
```

**출력**

```
[
  { "_id": "A", "percentiles": [72, 90] },
  { "_id": "B", "percentiles": [75, 88] }
]
```

## 표현식 사용 예제(MongoDB Shell)
<a name="percentile-expression-examples"></a>

연`$percentile`산자를 `$project` 단계 내의 표현식으로 사용하여 배열 필드의 백분위수를 계산할 수도 있습니다.

**샘플 문서 생성**

```
db.surveys.insertMany([
  { _id: 1, responses: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] },
  { _id: 2, responses: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] }
]);
```

**쿼리 예제**

```
db.surveys.aggregate([
  { $project: {
      quartiles: { $percentile: { input: "$responses", p: [0.25, 0.5, 0.75], method: "approximate" } }
    }}
]);
```

**출력**

```
[
  { "_id": 1, "quartiles": [6, 10, 16] },
  { "_id": 2, "quartiles": [5, 9, 15] }
]
```

## 코드 예제
<a name="percentile-code"></a>

`$percentile` 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누적기 사용량()과 표현식 사용량(`$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: percentiles across grouped documents
    const students = db.collection('students');
    const accumulatorResult = await students.aggregate([
      { $group: {
          _id: "$class",
          percentiles: { $percentile: { input: "$score", p: [0.25, 0.75], method: "approximate" } }
        }}
    ]).toArray();
    console.log('Accumulator result:', accumulatorResult);

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

        # Expression usage: percentiles of an array field
        surveys = db['surveys']
        expression_result = list(surveys.aggregate([
            { '$project': {
                'quartiles': { '$percentile': { 'input': '$responses', 'p': [0.25, 0.5, 0.75], 'method': 'approximate' } }
            }}
        ]))
        print('Expression result:', expression_result)

    finally:
        client.close()

example()
```

------