$max (Keep Larger Value)
Last updated: 2026-10-09
$max (Keep Larger Value)
$max writes the given value only when it is larger than the current field value. `{ $max: { highScore: 980 } }`. The field is created if missing. Ideal for tracking the high score or all-time high — a keep-the-maximum update, complementary to $min.
| Category | Update Field |
|---|---|
| MongoDB Version | 2.6+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $max: { <field>: <value> } }
⚙️ Parameters
| field | The field to compare and update. |
|---|---|
| value | The candidate value; written only if larger. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $max: only increases, never decreases
// 950 -> 980 since 980 is larger
// 990 stays since 980 is smaller
db.games.updateOne(
{ _id: 1 },
{ $max: { highScore: 980 } }
)
Output:
// Updated to 980 only when the current value is below it; otherwise untouched
📌 Notes
- Creates the field if missing
- Great for leaderboard highs and record levels
- Pair with $min to maintain data bounds
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QHow do I keep the high score with $max?
AUpdate with { $max: { highScore: score } } each time; lower scores are ignored automatically.
QWhat is the difference between $max and $set?
A$set overwrites unconditionally; $max updates only when the value is larger.
QIs $max atomic?
AYes.