View a markdown version of this page

$min - Amazon DocumentDB

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

$min

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

파라미터

  • expression: 평가할 표현식입니다. 필드 경로, 변수 또는 값으로 확인되는 표현식일 수 있습니다.

예제(MongoDB 쉘)

다음 예제에서는 연$min산자를 사용하여 여러 문서에서 age 필드의 최소값을 찾는 방법을 보여줍니다.

샘플 문서 생성

db.users.insertMany([ { name: "John", age: 35 }, { name: "Jane", age: 28 }, { name: "Bob", age: 42 }, { name: "Alice", age: 31 } ]);

쿼리 예제

db.users.aggregate([ { $group: { _id: null, minAge: { $min: "$age" } } }, { $project: { _id: 0, minAge: 1 } } ])

출력

[ { minAge: 28 } ]

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

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

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

참고

에서 창 연산자로 사용할 경우 $setWindowFields$min는 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: { lowestSoFar: { $min: "$price", window: { documents: ["unbounded", "current"] } } } } } ]);

출력

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

각 문서는 현재 문서까지 파티션 price 내에서 실행되는 최소 lowestSoFar인 로 보강됩니다.

코드 예제

$min 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누산기 사용량()과 창 연산자 사용량($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: minimum value across a group const users = db.collection('users'); await users.insertMany([ { name: "John", age: 35 }, { name: "Jane", age: 28 }, { name: "Bob", age: 42 }, { name: "Alice", age: 31 } ]); const accumulatorResult = await users.aggregate([ { $group: { _id: null, minAge: { $min: "$age" } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Window operator usage: running minimum 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: { lowestSoFar: { $min: "$price", window: { documents: ["unbounded", "current"] } } } } } ]).toArray(); console.log('Window result:', windowResult); 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: minimum value across a group users = db.users users.insert_many([ { "name": "John", "age": 35 }, { "name": "Jane", "age": 28 }, { "name": "Bob", "age": 42 }, { "name": "Alice", "age": 31 } ]) accumulator_result = list(users.aggregate([ { "$group": { "_id": None, "minAge": { "$min": "$age" } } } ])) print('Accumulator result:', accumulator_result) # Window operator usage: running minimum 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": { "lowestSoFar": { "$min": "$price", "window": { "documents": ["unbounded", "current"] } } } } } ])) print('Window result:', window_result) client.close() example()