MongoDB – $min operator
MongoDB $min or minimum operator is one of the field update operators. $min operator updates the field with the specified value if the specified value is less than the current value.
The $min
operator will compare the values of different data types according to the BSON comparison order. This operator can also be used in embedded/nested documents using dot notation.
One can use this operator in methods like update(), updateOne(), etc. according to your requirements. If the given field does not exist, then this operator will create a field and set the value of that field.
Syntax
{ $min: { field1: value1, field2: value2 ... } }
MongoDB $min Operator Example
In the following examples, we are working with:
Database: w3wiki
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.
Example 1: Comparing values (or numbers) using $min
operator
In this example, we are comparing values (or numbers) of the salary fields with the specified value, i.e, 2000. Here, the specified value is less than the current value. So. $min
operator updates the value of the salary field with the help of update() method to 2000.
Query:
db.contributor.update({name: "Priya"}, {$min: {"personal.rank": 30}})
Output:
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.
Query:
db.contributor.update({name: "Mohit"}, {$min: {salary: 4000}})
Output:
Example 2: Comparing values (or numbers) in nested documents using $min
operator
In this example, we are comparing values(or numbers) of the rank fields with the specified value, i.e, 13. Here, the specified value is less than the current value. So, $min
operator updates the value of the salary field with the help of update() method to 13.
Query:
db.contributor.update({name: "Priya"}, {$min: {"personal.rank": 13}})
Output:
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., 30.
Query:
db.contributor.update({name: "Priya"}, {$min: {"personal.rank": 30}})
Output:
Key Takeaways About $min Operator
- The $min operator in MongoDB updates a field with a specified value if it is less than the current value.
- It compares values of different data types according to the BSON comparison order.
- min operator creates the field and sets its value to the specified value if the field does not exist.
- The $min operator is used in methods like update(), updateOne(), etc., as per requirements.
Contact Us