For MongoDB I'm looking for atomic update that will increment field and if that increment will exceeds maximum given number it will stat that maximum number. Same behavior can be achieved with combination of $inc and $min operators but sadly not in one atomic update. Look at example below.
Example document
{
"_id": 1,
"i": 0
}
Queries
db.test.update({_id:1}, {$set:{"a":"foo"}, $inc:{i:1}}); db.test.update({_id:1}, {$min:{i:2}});
db.test.update({_id:1}, {$set:{"b":"bar"}, $inc:{i:1}}); db.test.update({_id:1}, {$min:{i:2}});
db.test.update({_id:1}, {$set:{"c":"baz"}, $inc:{i:1}}); db.test.update({_id:1}, {$min:{i:2}});
Result document
{
"_id": 1,
"i": 2,
"a": "foo",
"b": "bar",
"c": "baz"
}
Update
Thanks to Christian P answer I realized that I forgot to mention one more condition. I need document to be updated because I need update more fields than is shown in example. In fact I need increment ceiling (maximum) condition in update statement. I've updated my example to make this clear.
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.
MongoDB provides different types of field update operators to update the values of the fields in the documents and the maximum operator ( $max ) is one of them. This operator updates the field with the specified value if the specified value is greater than the current value.
In MongoDB, the $set operator is used to replace the value of a field to the specified value. If the given field does not exist in the document, the $set operator will add the field to the specified value. Our database name is 'myinfo' and our collection name is "employee".
You're looking for a findAndModify command:
db.test.findAndModify({
query: { _id: 1, i: { $lt: 2 } },
update: { $inc: { i: 1 } }
})
This query will update the document only if i
is not greater than your maximum given value..
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