

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

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

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

Amazon DocumentDB의 `$maxN` 연산자는 N개의 가장 큰 값을 반환합니다. `$group` 단계에서 누적기로 사용할 경우 각 그룹의 N 최대값 배열을 반환합니다. 배열 표현식 연산자로 사용할 경우 배열의 N 최대 요소를 반환합니다.

**파라미터**
+ `input`: 최대값을 반환할 배열 또는 필드로 확인되는 표현식입니다`n`.
+ `n`: 반환할 최대값 수를 지정하는 양의 정수로 확인되는 표현식입니다.

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

**배열 표현식 연산자 동작**
+ 보다 `n` 작은 값은 지정할 수 없습니다`1`.
+ `$maxN`는 `input` 배열에서 찾은 `null` 값을 필터링합니다.
+ 지정된 `n`가 `input` 배열의 요소 수보다 크거나 같으면는 `input` 배열의 모든 요소를 `$maxN` 반환합니다.
+ 가 배열이 아닌 값으로 `input` 확인되면 집계 작업 오류가 발생합니다.
+ 에 숫자 및 문자열 요소가 모두 `input` 포함된 경우 문자열 요소는 BSON 비교 순서에 따라 숫자 요소 앞에 정렬됩니다.

**누산기 동작**
+ 누적기로 사용할 경우는 상수이거나의 `_id` 값에 따라 달라지는 양의 정수 표현식이어야 `n` 합니다`$group`.
+ `$maxN`는 null 및 누락 값을 필터링합니다.
+ 그룹에 개 미만의 `n` 요소가 포함된 경우는 그룹의 모든 요소를 `$maxN` 반환합니다.
+ `$maxN`는 BSON 비교 순서에 따라 입력 데이터를 비교하여 적절한 출력 유형을 결정합니다. 입력 데이터에 여러 데이터 형식이 포함된 경우 `$maxN` 출력 형식은 비교 순서에서 가장 높습니다.

**출력 순서 지정**

`$maxN`는 특정 정렬 순서로 값을 반환하지 않습니다. 특정 정렬 순서를 보장해야 하는 경우 `$topN` 대신를 사용하거나 결과를 로 래핑합니다`$sortArray`.

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

다음 예제에서는 `$maxN` 누적기를 사용하여 각 주제에 대해 가장 높은 두 점수를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.scores.insertMany([
  { subject: "math", score: 85 },
  { subject: "math", score: 72 },
  { subject: "math", score: 93 },
  { subject: "math", score: 68 },
  { subject: "science", score: 90 },
  { subject: "science", score: 78 },
  { subject: "science", score: 65 },
  { subject: "science", score: 88 }
]);
```

**쿼리 예제**

```
db.scores.aggregate([
  { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } }
]);
```

**출력**

```
[
  { "_id": "math", "highestTwo": [85, 93] },
  { "_id": "science", "highestTwo": [88, 90] }
]
```

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

연`$maxN`산자를 `$project` 스테이지 내의 표현식으로 사용하여 배열 필드에서 가장 큰 N 요소를 반환할 수도 있습니다.

**샘플 문서 생성**

```
db.readings.insertMany([
  { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] },
  { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] }
]);
```

**쿼리 예제**

```
db.readings.aggregate([
  { $project: {
      highestThree: { $maxN: { input: "$values", n: 3 } }
    }}
]);
```

**출력**

```
[
  { "_id": 1, "highestThree": [45, 56, 78] },
  { "_id": 2, "highestThree": [44, 90, 67] }
]
```

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

`$maxN` 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누적기 사용량()과 표현식 사용량(`$group`)을 모두 보여줍니다. `$project` 

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');

    // Accumulator usage: N largest values per group
    const scores = db.collection('scores');
    const accumulatorResult = await scores.aggregate([
      { $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } }
    ]).toArray();
    console.log('Accumulator result:', accumulatorResult);

    // Expression usage: N largest elements from an array field
    const readings = db.collection('readings');
    const expressionResult = await readings.aggregate([
      { $project: { highestThree: { $maxN: { input: "$values", n: 3 } } } }
    ]).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: N largest values per group
        scores = db['scores']
        accumulator_result = list(scores.aggregate([
            { '$group': { '_id': '$subject', 'highestTwo': { '$maxN': { 'input': '$score', 'n': 2 } } } }
        ]))
        print('Accumulator result:', accumulator_result)

        # Expression usage: N largest elements from an array field
        readings = db['readings']
        expression_result = list(readings.aggregate([
            { '$project': { 'highestThree': { '$maxN': { 'input': '$values', 'n': 3 } } } }
        ]))
        print('Expression result:', expression_result)

    finally:
        client.close()

example()
```

------