定義
$minThe
$minupdates the value of the field to a specified value if the specified value is less than the current value of the field. The$minoperator can compare values of different types, using the BSON comparison order.{ $min: { <field1>: <value1>, ... } } <field>を埋め込みドキュメントまたは配列で指定するには、ドット表記を使用します。
動作
MongoDB 5.0 以降、更新演算子では名前が文字列ベースのドキュメントフィールドを辞書順に処理します。数値名のフィールドは、数値順に処理されます。詳細については、「更新演算子の動作」を参照してください。
If the field does not exist, the $min operator sets the field to the specified value.
For comparisons between values of different types, such as a number and a null, $min uses the BSON comparison order.
Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $min 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).
例
$minを使用して数値を比較
scores コレクションを次のように作成します。
db.scores.insertOne( { _id: 1, highScore: 800, lowScore: 200 } )
The lowScore for the document currently has the value 200. The following operation uses $min to compare 200 to the specified value 150 and updates the value of lowScore to 150 since 150 is less than 200:
db.scores.updateOne( { _id: 1 }, { $min: { lowScore: 150 } } )
scoresコレクションには、次の変更されたドキュメントが含まれています。
{ _id: 1, highScore: 800, lowScore: 150 }
次の操作は、フィールドlowScoreの現在の値、つまり150が250より小さいため効果がありません。
db.scores.updateOne( { _id: 1 }, { $min: { lowScore: 250 } } )
scoresコレクションではドキュメントは変更されていません。
{ _id: 1, highScore: 800, lowScore: 150 }
$min を使用して日付を比較
tags コレクションを次のように作成します。
db.tags.insertOne( { _id: 1, desc: "crafts", dateEntered: ISODate("2013-10-01T05:00:00Z"), dateExpired: ISODate("2013-10-01T16:38:16Z") } )
次の操作では、 dateEnteredフィールドの現在の値、つまりISODate("2013-10-01T05:00:00Z")と指定された日付new Date("2013-09-25")とを比較して、フィールドを更新するかどうかを判断します。
db.tags.updateOne( { _id: 1 }, { $min: { dateEntered: new Date("2013-09-25") } } )
この操作によりdateEnteredフィールドが更新されます。
{ _id: 1, desc: "crafts", dateEntered: ISODate("2013-09-25T00:00:00Z"), dateExpired: ISODate("2013-10-01T16:38:16Z") }