MongoDB field increment with maximum condition in update statement

For MongoDB, I am looking for an atomic update that will increase the field, and if this increment exceeds the maximum given number, it will indicate this maximum number. The same behavior can be achieved with a combination of the $ inc and $ min operators, but, unfortunately, not in one atomic update. See an example below.

Document example

{ "_id": 1, "i": 0 } 

Inquiries

 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}}); 

Results Document

 { "_id": 1, "i": 2, "a": "foo", "b": "bar", "c": "baz" } 

Update

Thanks to Christian P's answer, I realized that I forgot to mention one more condition. I need a document to update because I need to update more fields than shown in the example. In fact, I need the condition for maximum growth (maximum) in the update statement. I updated my example to make this clear.

+6
source share
1 answer

You are looking for the findAndModify command:

 db.test.findAndModify({ query: { _id: 1, i: { $lt: 2 } }, update: { $inc: { i: 1 } } }) 

This request will update the document only if i does not exceed your maximum specified value.

+5
source

Source: https://habr.com/ru/post/970991/


All Articles