Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB field increment with max condition in update statement

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.

like image 495
michal.kreuzman Avatar asked Jun 18 '14 08:06

michal.kreuzman


People also ask

How to update increment in MongoDB?

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.

How to use$ max in MongoDB?

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.

How use MongoDB $set?

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".


1 Answers

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..

like image 125
Christian P Avatar answered Sep 20 '22 16:09

Christian P