The $min operator in MongoDB updates a field only when the new value is smaller than the current value, helping enforce minimum limits and keep data consistent.
Conditional Update: Changes a value only when the new value is smaller.
Minimum Thresholds: Helps enforce lower bounds on fields like rank or score.
Nested Fields: Supports updates on embedded fields using dot notation.
Auto Field Creation: Creates the field if it doesnβt exist.
BSON Comparison: Compares values using BSON type-aware rules.
Syntax
{ $min: { field1: value1, field2: value2 ... } }
$min: Operator that applies conditional minimum updates.
field1, field2: Target fields to be checked and updated.
value1, value2: New values to compare against current values.
Examples of Using the $min Operator
We have a MongoDB collection for contributors with the following structure:
Database: GeeksforGeeks
Collection: contributor
Document: Three documents that contain the details of the contributors in the form of field-value pairs.
We compare the existing salary field with the specified value 2000. Since 2000 is smaller than the current value, the $min operator will update the salary field to 2000.
Using dot notation, the $min operator compares the current value of the field inside the embedded documents (personal.rank) with the specified value 13.