MongoDB has a $min
operator that allows you to update the value of a field only if the specified value is less than the current value of the field.
In other words, if the $min
value is less than the current value in the document, the $min
value is used. Otherwise, the document’s value remains unchanged.
Example
Suppose we have a collection called golf
with the following document:
{ "_id" : 1, "strokes" : 70 }
And imagine that we update the document after each game of golf with the latest score. In this case, we would only want the strokes
field to be updated if our latest score was lower than our previous score.
In this case we could use the $min
operator to achieve that outcome.
Example:
db.golf.update(
{ _id: 1 },
{ $min: { strokes: 64 } }
)
Output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
This message tells us that one document matched and was updated.
Let’s check the collection again.
db.golf.find()
Result:
{ "_id" : 1, "strokes" : 64 }
We can see that the strokes
field was updated with the new value. This is because 64 is lower than its previous value of 70.
When the Value is Higher
When the value specified with $min
is higher than the existing value in the document, nothing is updated.
Example:
db.golf.update(
{ _id: 1 },
{ $min: { strokes: 72 } }
)
Output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
We can see by the message that nothing was updated.
Let’s check the collection again.
db.golf.find()
Result:
{ "_id" : 1, "strokes" : 64 }
We can see that the value remains at 64, even though we tried to update it to 72. This is expected, because we used $min
.
Dates
You can use $min
on date fields.
Suppose we have a collection
called species with the following document:
{ "_id" : 1, "firstDiscovered" : ISODate("2000-01-01T00:00:00Z") }
Let’s try to update the date with a date that’s later than the current date in the document.
db.species.update(
{ _id: 1 },
{ $min: { firstDiscovered: new Date("2001-01-01") } }
)
Here, we try to update the year from 2000
to 2001
. Given the new date is later than the existing one, we get the following:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
Nothing was updated.
Let’s check the collection:
db.species.find()
Result:
{ "_id" : 1, "firstDiscovered" : ISODate("2000-01-01T00:00:00Z") }
As expected, the same date value remains.
Now let’s try to update it with an earlier date.
db.species.update(
{ _id: 1 },
{ $min: { firstDiscovered: new Date("1999-01-01") } }
)
Output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
We can see by the message that the document was updated.
Let’s check.
db.species.find()
Result:
{ "_id" : 1, "firstDiscovered" : ISODate("1999-01-01T00:00:00Z") }
The date was updated as expected.