Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Perform conditional upserts or updates in MongoDB
In MongoDB, you can perform conditional updates that only modify a field if certain conditions are met. The $max operator is particularly useful for conditional updates - it only updates a field if the new value is greater than the current value.
Syntax
db.collection.update(
{ "field": "matchValue" },
{ $max: { "fieldToUpdate": newValue } }
);
Sample Data
Let us create a collection with sample student score documents ?
db.conditionalUpdatesDemo.insertMany([
{
"_id": 100,
"StudentFirstScore": 89,
"StudentSecondScore": 78,
"BiggestScore": 89
},
{
"_id": 101,
"StudentFirstScore": 305,
"StudentSecondScore": 560,
"BiggestScore": 1050
},
{
"_id": 103,
"StudentFirstScore": 560,
"StudentSecondScore": 789,
"BiggestScore": 880
}
]);
{
"acknowledged": true,
"insertedIds": [100, 101, 103]
}
Display all documents from the collection ?
db.conditionalUpdatesDemo.find().pretty();
{
"_id": 100,
"StudentFirstScore": 89,
"StudentSecondScore": 78,
"BiggestScore": 89
}
{
"_id": 101,
"StudentFirstScore": 305,
"StudentSecondScore": 560,
"BiggestScore": 1050
}
{
"_id": 103,
"StudentFirstScore": 560,
"StudentSecondScore": 789,
"BiggestScore": 880
}
Example: Conditional Update with $max
Update the BiggestScore field to 150, but only if 150 is greater than the current value ?
db.conditionalUpdatesDemo.update(
{ "_id": 100 },
{ $max: { "BiggestScore": 150 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Check if the BiggestScore field was updated for document with _id 100 ?
db.conditionalUpdatesDemo.find();
{
"_id": 100,
"StudentFirstScore": 89,
"StudentSecondScore": 78,
"BiggestScore": 150
}
{
"_id": 101,
"StudentFirstScore": 305,
"StudentSecondScore": 560,
"BiggestScore": 1050
}
{
"_id": 103,
"StudentFirstScore": 560,
"StudentSecondScore": 789,
"BiggestScore": 880
}
Key Points
- The
$maxoperator only updates the field if the new value is greater than the existing value - If the new value is smaller or equal, no update occurs
- This provides automatic conditional logic without complex queries
Conclusion
The $max operator provides an elegant solution for conditional updates in MongoDB, automatically comparing values and updating only when the new value exceeds the current one. This is particularly useful for maintaining maximum scores or highest values.
