View a markdown version of this page

$max - Amazon DocumentDB

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

$max

$max 집계 연산자는 문서 세트에서 지정된 필드의 최대값을 반환합니다. 이 연산자는 문서 세트에서 가장 높은 값을 찾는 데 유용합니다.

파라미터

  • expression: 최대값을 계산하는 데 사용할 표현식입니다.

예제(MongoDB 쉘)

다음 예제에서는 $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 } ]

창 연산자 사용 예제(MongoDB Shell)

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

연$max산자는 $setWindowFields 스테이지에서 창 연산자로 사용할 수도 있습니다. 이 컨텍스트에서는 각 창의 문서에 대한 최대값을 반환합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.

참고

에서 창 연산자로 사용할 경우 $setWindowFields$max는 100MB의 중간 데이터로 제한됩니다. 이 제한을 초과하는 작업은 오류를 반환합니다.

샘플 문서 생성

db.stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]);

쿼리 예제

다음 예제에서는 문서를 로 분할하고ticker, 각 파티션을 로 정렬하고hour, 파티션 시작부터 현재 문서까지 가장 높은 가격을 반환합니다.

db.stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { highestSoFar: { $max: "$price", window: { documents: ["unbounded", "current"] } } } } } ]);

출력

[ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "highestSoFar": 50 }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "highestSoFar": 50 }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "highestSoFar": 60 }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "highestSoFar": 60 }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "highestSoFar": 30 }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "highestSoFar": 35 }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "highestSoFar": 35 } ]

각 문서는 현재 문서를 포함하여 파티션 price 내에서 highestSoFar실행 중인 최대 인 로 보강됩니다.

코드 예제

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

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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'); // Accumulator usage: maximum value across a group const students = db.collection('students'); await students.insertMany([ { name: "John", score: 85 }, { name: "Jane", score: 92 }, { name: "Bob", score: 78 }, { name: "Alice", score: 90 } ]); const accumulatorResult = await students.aggregate([ { $group: { _id: null, maxScore: { $max: "$score" } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: running maximum within each partition const stockPrices = db.collection('stockPrices'); await stockPrices.insertMany([ { _id: 1, ticker: "ABC", hour: 1, price: 50 }, { _id: 2, ticker: "ABC", hour: 2, price: 45 }, { _id: 3, ticker: "ABC", hour: 3, price: 60 }, { _id: 4, ticker: "ABC", hour: 4, price: 40 }, { _id: 5, ticker: "XYZ", hour: 1, price: 30 }, { _id: 6, ticker: "XYZ", hour: 2, price: 35 }, { _id: 7, ticker: "XYZ", hour: 3, price: 25 } ]); const windowResult = await stockPrices.aggregate([ { $setWindowFields: { partitionBy: "$ticker", sortBy: { hour: 1 }, output: { highestSoFar: { $max: "$price", window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); 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') db = client['test'] # Accumulator usage: maximum value across a group students = db.students students.insert_many([ { "name": "John", "score": 85 }, { "name": "Jane", "score": 92 }, { "name": "Bob", "score": 78 }, { "name": "Alice", "score": 90 } ]) accumulator_result = list(students.aggregate([ { "$group": { "_id": None, "maxScore": { "$max": "$score" } } } ])) print('Accumulator result:', accumulator_result) # Window operator usage: running maximum within each partition stock_prices = db.stockPrices stock_prices.insert_many([ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50 }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45 }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60 }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40 }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30 }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35 }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25 } ]) window_result = list(stock_prices.aggregate([ { "$setWindowFields": { "partitionBy": "$ticker", "sortBy": { "hour": 1 }, "output": { "highestSoFar": { "$max": "$price", "window": { "documents": ["unbounded", "current"] } } } } } ])) print('Window result:', window_result) client.close() example()