How to update a field in a MongoDB document only if the new value is greater then the current value?
Any solution?
db.report.update(
{ _id: 1234 },
{
$setIfGreater: {
A: 10
}
})
The way we do this is by $project ing our documents and using the $concat string aggregation operator to return the concatenated string. You then iterate the cursor and use the $set update operator to add the new field to your documents using bulk operations for maximum efficiency.
In MongoDB, the $inc operator is used to increment the value of a field by a specified amount. The $inc operator adds as a new field when the specified field does not exist, and sets the field to the specified amount. The $inc accepts positive and negative value as an incremental amount.
You can use the $max
operator to do this:
db.report.update(
{ _id: 1234 },
{
$inc: { A: 5 },
$set: {
B: "ABC123",
}
$max: {
C: 10
}
})
The
$max
operator updates the value of the field to a specified value if the specified value is greater than the current value of the field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With