정의
$max$max연산자 지정된 값이 필드 의 현재 값보다 큰 경우 필드 값을$max지정된 값으로 업데이트합니다. 연산자 BSON비교 순서를 사용하여 서로 다른 유형의 값을 비교할 수 있습니다.연산자 표현식 형식은 다음과
$max같습니다.{ $max: { <field1>: <value1>, ... } } 내장된 문서나 배열에
<field>기호를 지정하려면 점 표기법을사용하십시오.
행동
MongoDB 5.0부터 업데이트 연산자는 문자열 기반 이름이 있는 문서 필드를 사전순으로 처리합니다. 숫자 이름이 있는 필드는 숫자 순서대로 처리됩니다. 자세한 내용은 업데이트 운영자 동작을 참조하십시오.
If the field does not exists, the $max operator sets the field to the specified value.
Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $max with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).
예시
$max 를 사용하여 숫자 비교
scores 컬렉션을 생성합니다.
db.scores.insertOne( { _id: 1, highScore: 800, lowScore: 200 } )
문서의 highScore는 현재 800입니다. 다음 작업은 다음을 수행합니다.
highscore(800)를 지정된 값(950)과 비교합니다.950이 800보다 크므로
highScore를 950으로 업데이트합니다.
db.scores.updateOne( { _id: 1 }, { $max: { highScore: 950 } } )
이제 scores 컬렉션에 다음과 같이 수정된 문서가 포함되어 있습니다.
{ _id: 1, highScore: 950, lowScore: 200 }
highScore의 값인 950이 870보다 크므로 다음 작업은 효과가 없습니다.
db.scores.updateOne( { _id: 1 }, { $max: { highScore: 870 } } )
문서가 scores 컬렉션에서 변경되지 않은 상태로 유지됩니다.
{ _id: 1, highScore: 950, lowScore: 200 }
$max 를 사용하여 날짜 비교
tags 컬렉션을 생성합니다.
db.tags.insertOne( { _id: 1, desc: "crafts", dateEntered: ISODate("2013-10-01T05:00:00Z"), dateExpired: ISODate("2013-10-01T16:38:16.163Z") } )
다음 작업은 dateExpired 필드의 현재 값인 ISODate("2013-10-01T16:38:16.163Z")를 지정된 날짜 new Date("2013-09-30")와 비교하여 필드 업데이트 여부를 결정합니다.
db.tags.updateOne( { _id: 1 }, { $max: { dateExpired: new Date("2013-09-30") } } )
new Date("2013-09-30") 최신 날짜가 아니므로 작업은 dateExpired 필드를 업데이트하지 않습니다.
{ _id: 1, desc: "decorative arts", dateEntered: ISODate("2013-10-01T05:00:00Z"), dateExpired: ISODate("2013-10-01T16:38:16.163Z") }