Along with traditional updates (i.e. replacing an entire document), MongoDB supports atomic, in-place updates with modifier operations, allowing you to update existing values for a document.
Let’s start with a simple Page model:
The atomic modifier operations can be performed directly on instances of your MongoMapper class, or on a collection by passing in the ID (s) or criteria of the documents you wish to modify.
Increment the given keys by the values specified.
Decrement the given keys by the values specified.
Set the values for the keys.
Unset or remove the given keys.
Append one value to the array key.
Append several values to the array key.
Append one unique value to the array key.
Remove one value from the array key.
Remove several values from the array key.
Remove the last element from the array key.
Note that if you pass -1, it will remove the first element from the array.
An options hash can be passed as the final argument. These options will be passed to the Ruby driver’s update method.
For example, even though a model’s safe setting will not apply to modifier operations, atomic updates can still be safe:
Or, to do an upsert:
Please note that MongoMapper always sets the
:multi option to
true. This cannot be overridden.
When applying a modifier operation on a variable (local or instance), make sure to reload the variable. MongoMapper does not update the state of the variable unless you explicitly tell it to like so:
MongoDB Modifier Operations Documentation