Database Reference
In-Depth Information
In this example, you incremented Tracklist.Track using the track list title as an identifier. But now consider
what happens if the track list data is changed by another user using the same method while MongoDB was modifying
your data. Because Tracklist.Title remains the same, you might assume (incorrectly) that you are updating the
original data, when in fact you are overwriting the changes.
This is known as the ABA problem . This scenario might seem unlikely, but in a multi-user environment, where
many applications are working on data at the same time, this can be a significant problem.
To avoid this problem, you can do one of the following:
Use the entire object in the update's query expression, instead of just the
_id and
comments.by field.
Use
$set to set the field you care about. If other fields have changed, they won't be affected
by this.
Put a version variable in the object and increment it on each update.
When possible, use a
$ operator instead of an update-if-current sequence of operations.
MongoDB does not support updating multiple documents atomically in a single operation. instead, you can use
nested objects, which effectively make them one document for atomic purposes.
Note
Modifying and Returning a Document Atomically
The findAndModify command also allows you to perform an atomic update on a document. This command modifies
the document and returns it. The command takes three main operators: <query> , which you use to specify the
document you're executing it against; <sort> , used to sort the matching documents when multiple match, and
<operations> , which you use to specify what needs to be done.
Now let's look at a handful of examples that illustrate how to use this command. The first example finds the
document you're searching for and removes it once it is found:
> db.media.findAndModify( { "Title" : "One Piece",sort:{"Title": -1}, remove:
true} )
{
"_id" : ObjectId("4c445218c603000000007ede"),
"Type" : "Manga",
"Title" : "One Piece",
"Volumes" : 612,
"Read" : 524
}
This code returned the document it found matching the criteria. In this case, it found and removed the first item
it found with the title “One Piece.” If you execute a find() function now, you will see that the document is no longer
within the collection.
The next example modifies the document rather than removing it:
> db.media.findAndModify( { query: { "ISBN" : "987-1-4302-3051-9" }, sort:
{"Title":-1}, update: {$set: {"Title" : " Different Title"} } } )
 
 
Search WWH ::




Custom Search