0
0
MongoDBquery~5 mins

$min and $max update operators in MongoDB

Choose your learning style9 modes available
Introduction

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.

When you want to save the lowest score a player has achieved in a game.
When tracking the highest temperature recorded in a day.
When updating a product price only if the new price is lower or higher than the current price.
When storing the earliest or latest date of an event without overwriting better data.
Syntax
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.

Examples
This sets Alice's score to 50 only if her current score is higher than 50 or missing.
MongoDB
db.players.updateOne(
  { name: "Alice" },
  { $min: { score: 50 } }
)
This updates Paris's temperature to 30 only if the current temperature is less than 30 or missing.
MongoDB
db.weather.updateOne(
  { city: "Paris" },
  { $max: { temperature: 30 } }
)
This sets the price to 100 only if the current price is higher than 100 or missing, and sets highPrice to 200 only if the current highPrice is less than 200 or missing.
MongoDB
db.products.updateOne(
  { productId: 123 },
  { $min: { price: 100 }, $max: { highPrice: 200 } }
)
Sample Program

This example inserts a player Bob with scores, then updates his highScore only if 90 is higher, and lowScore only if 15 is lower.

MongoDB
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" })
OutputSuccess
Important Notes

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.

Summary

$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.