Database Reference
In-Depth Information
A standard behavior when executing atomic operations is that the data will be locked and therefore unable to
be reached by other queries. However, MongoDB does not support locking or complex transactions for a number
of reasons:
In sharded environments (see Chapter 12 for more information on such environments),
distributed locks can be expensive and slow. MongoDB's goal is to be lightweight and fast,
so expensive and slow goes against the principle.
MongoDB developers don't like the idea of deadlocks. In their view, it's preferable for a system
to be simple and predictable instead.
MongoDB is designed to work well for real-time problems. When an operation is executed
that locks large amounts of data, it would also stop some smaller light queries for an extended
period of time. Again, this goes against the MongoDB goal of speed.
MongoDB includes several update operators (as noted previously), all of which can atomically update
an element:
$set : Sets a particular value.
$unset : Removes a particular value.
$inc : Increments a particular value by a certain amount.
$push : Appends a value to an array.
$pull : Removes one or more values from an existing array.
$pullAll : Removes several values from an existing array.
Using the Update if Current Method
Another strategy that atomic update uses is the update-if-current method. This method takes the following three steps:
1.
It fetches the object from the document.
2.
It modifies the object locally (with any of the previously mentioned operations,
or a combination of them).
3. It sends an update request to update the object to the new value, in case the current value
still matches the old value fetched.
You can use the getlasterror method to check whether all went well. Note that all of this happens automatically.
Let's take a new look at an example shown previously:
> db.media.update( { "Tracklist.Title" : "Been a son"},
{$inc:{"Tracklist.$.Track" : 1} } )
Now you can use the getlasterror command to check whether the update went smoothly:
> db.$cmd.findOne({getlasterror:1})
If the atomic update executes successfully, you get the following result back:
{ "err" : null, "updatedExisting" : true, "n" : 1, "ok" : 1 }
 
Search WWH ::




Custom Search