MongoDB – Maximum operator ( $max )
MongoDB provides different types of field update operators to update the values of the fields in the documents and the maximum operator ( $max ) is one of them. This operator updates the field with the specified value if the specified value is greater than the current value.
- This operator will compare the values of different data types according to the BSON comparison order.
- You can also use this operator in embedded/nested documents using dot notation.
- You can use this operator in methods like update(), updateOne() etc. according to your requirements.
- If the given field does not exists, then this operator will create field and set the value of that field.
Syntax:
{ $max: { field1: value1, field2: value2 ... } }
In the following examples, we are working with:
Database: GeeksforGeeks Collection: contributor Document: three documents that contain the details of the contributors in the form of field-value pairs.
Comparing values (or numbers) using $max operator:
In this example, we are 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.
Python3
db.contributor.update({name: "Mohit" }, {$ max : {salary: 5000 }}) |
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.
Python3
db.contributor.update({name: "Mohit" }, {$ max : {salary: 4000 }}) |
Comparing values (or numbers) in nested documents using $max operator:
In this example, we are 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 salary field with the help of update() method to 30.
Python3
db.contributor.update({name: "Priya" }, {$ max : { "personal.rank" : 30 }}) |
If the current value of the rank field is less than the specified value, then this operator will not update the value of the rank field with the specified value, i.e., 13.
Python3
db.contributor.update({name: "Priya" }, {$ max : { "personal.rank" : 13 }}) |
Please Login to comment...