$max

Updates a field only if the specified value is greater than the current field value, useful for maintaining maximum values.

Syntax

{ $max: { <field1>: <value1>, <field2>: <value2>, ... } }

Parameters

fieldstringrequired

Field name to update with maximum value

valueobjectrequired

Value to compare with current field value

Examples

Update maximum score

Update high score only if new score is greater

Query:

db.players.updateOne({ playerId: "player123" }, { $max: { highScore: 1500 } })

Output:

Updates highScore to 1500 only if current value is less than 1500

Track maximum temperature

Update maximum recorded temperature for a sensor

Query:

db.sensors.updateOne({ sensorId: "temp01" }, { $max: { maxTemp: 98.6, lastReading: new Date() } })

Output:

Updates maxTemp only if 98.6 is greater than current maximum temperature

Related