These operators help you update a value only if the new value is smaller ($min) or larger ($max) than the current one. This keeps your data accurate without extra checks.
$min and $max update operators in MongoDB
db.collection.updateOne(
{ <filter> },
{ $min: { <field1>: <value1>, ... } }
)
// or
db.collection.updateOne(
{ <filter> },
{ $max: { <field2>: <value2>, ... } }
)
// or both together
db.collection.updateOne(
{ <filter> },
{ $min: { <field1>: <value1>, ... }, $max: { <field2>: <value2>, ... } }
)You can use $min and $max together or separately in the same update.
If the current field value is missing, $min and $max will set it to the given value.
db.players.updateOne(
{ name: "Alice" },
{ $min: { score: 50 } }
)db.weather.updateOne(
{ city: "Paris" },
{ $max: { temperature: 30 } }
)db.products.updateOne(
{ productId: 123 },
{ $min: { price: 100 }, $max: { highPrice: 200 } }
)This example inserts a player Bob with scores, then updates his highScore only if 90 is higher, and lowScore only if 15 is lower.
db.scores.insertOne({ player: "Bob", highScore: 80, lowScore: 20 })
// Try to update highScore to 90 only if it's higher
// Try to update lowScore to 15 only if it's lower
db.scores.updateOne(
{ player: "Bob" },
{ $max: { highScore: 90 }, $min: { lowScore: 15 } }
)
// Find the updated document
db.scores.findOne({ player: "Bob" })If the field does not exist, $min and $max will create it with the given value.
These operators only work with numbers, dates, and strings that can be compared.
They do not replace the value if the condition is not met, so your data stays safe.
$min updates a field only if the new value is smaller than the current one.
$max updates a field only if the new value is larger than the current one.
Use them to keep track of minimum or maximum values easily without extra code.