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

CategoryUpdate Field
MongoDB Version2.6+
Example Languagemongosh (Shell)

📝 Syntax

{ $max: { <field>: <value> } }

⚙️ Parameters

fieldThe field to compare and update.
valueThe 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏