MongoDB $max Operator (original) (raw)

Last Updated : 5 May, 2026

The $max operator updates a field only when the specified value is greater than the existing value in MongoDB, helping enforce thresholds and keep data accurate during updates.

Features of the $max Operator

Here are some features of $max Operator:

**Syntax

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

This syntax allows you to specify one or more fields and their corresponding values to update.

MongoDB $max Operator Examples

The following examples demonstrate how to use the $max operator in MongoDB to update fields conditionally based on the specified value. In the following examples, we are using:

Screenshot-2026-02-11-175920

Example 1: Comparing Values (or numbers) Using $max operator

Comparing values(or numbers) of the salary fields with the specified value, i.e., 5000. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 5000.

db.contributor.updateOne({name: "Ethan"}, {$max: {salary: 5000}})

**Output:

Screenshot-2026-02-11-180259

**Note: The collection.update() method is deprecated. Use updateOne() or updateMany() instead for clearer and safer updates.

If the current value of the salary field is greater than the specified value, then this operator will not update the value of the salary field with the specified value, i.e., 4000.

db.contributor.updateOne({name: "Ethan"}, {$max: {salary: 4000}})

**Output:

Screenshot-2026-02-11-180646

In this case, if the current value of salary is greater than 4000 (e.g., 5000), the field will not be updated.

Example 2: Comparing values (or numbers) in Nested Documents using $max operator

Comparing values (or numbers) of the rank fields with the specified value, i.e., 30. Here, the specified value is greater than the current value. So, $max operator updates the value of the rank field with the help of update() method to 30.

**Query:

db.contributor.updateOne({name: "Olivia"}, {$max: {"personal.rank": 30}})

**Output:

Screenshot-2026-02-11-181025

If the current value of the rank field is greater than the specified value, then this operator will not update the value of the rank field with the specified value, i.e., 13.

db.contributor.updateOne({name: "Olivia"}, {$max: {"personal.rank": 13}})

**Output:

Screenshot-2026-02-11-181142

Current value of personal.rank is greater than 13 (e.g., 30), the field will not be updated.

Important Points on $max Operator