

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

# \$1max
<a name="max"></a>

`$max` 집계 단계는 파이프라인 단계의 모든 문서에서 지정된 필드의 최대값을 반환하는 데 사용됩니다. 이 연산자는 문서 세트에서 가장 높은 값을 찾는 데 유용합니다.

**파라미터**
+ `expression`: 최대값을 계산하는 데 사용할 표현식입니다.

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

다음 예제에서는 `$max` 연산자를 사용하여 학생 문서 모음에서 최대 점수를 찾는 방법을 보여줍니다. `$group` 스테이지는 모든 문서를 그룹화하고 연`$max`산자는 모든 문서에서 `score` 필드의 최대값을 계산하는 데 사용됩니다.

**샘플 문서 생성**

```
db.students.insertMany([
  { name: "John", score: 85 },
  { name: "Jane", score: 92 },
  { name: "Bob", score: 78 },
  { name: "Alice", score: 90 }
])
```

**쿼리 예제**

```
db.students.aggregate([
  { $group: { _id: null, maxScore: { $max: "$score" } } },
  { $project: { _id: 0, maxScore: 1 } }
])
```

**출력**

```
[ { maxScore: 92 } ]
```

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

`$max` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

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

  const result = await students.aggregate([
    { $group: { _id: null, maxScore: { $max: "$score" } } }
  ]).toArray();

  console.log(result);
  await client.close();
}

findMaxScore();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def find_max_score():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    students = db.students

    result = list(students.aggregate([
        { "$group": { "_id": None, "maxScore": { "$max": "$score" } } }
    ]))

    print(result)
    client.close()

find_max_score()
```

------