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.
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
Increment the given keys by the values specified.
decrement
Decrement the given keys by the values specified.
set
Set the values for the keys.
unset
Unset or remove the given keys.
push
Append one value to the array key.
push_all
Append several values to the array key.
add_to_set, push_uniq
Append one unique value to the array key.
pull
Remove one value from the array key.
pull_all
Remove several values from the array key.
pop
Remove the last element from the array key.
Note that if you pass -1, it will remove the first element from the array.
Options
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.
Notes
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: