$max
The $max update operator updates a field's value only if the specified value is greater than the current field value. This operator is useful for maintaining maximum values across updates.
Parameters
-
field: The field to update. -
value: The value to compare with the current field value.
Example (MongoDB Shell)
The following example demonstrates using the $max operator to update the highest recorded score for a player.
Create sample documents
db.scores.insertMany([ { _id: 1, player: "Alice", highScore: 85 }, { _id: 2, player: "Bob", highScore: 92 }, { _id: 3, player: "Charlie", highScore: 78 } ])
Update example
db.scores.updateOne( { _id: 1 }, { $max: { highScore: 95 } } )
Result
The highScore field for Alice is updated to 95 because 95 is greater than the current value of 85.
{ "_id": 1, "player": "Alice", "highScore": 95 }
Code examples
To view a code example for using the $max command, choose the tab for the language that you want to use: