Databases Reference
In-Depth Information
{
"_id" : 123,
"apples" : 20,
"oranges : 3,
"total" : 2
}
Now, if you do an update that might or might not create a new field, do you increment
total or not? If the update ends up creating a new field, total should be updated:
> db.food.update({"_id" : 123}, {"$inc" : {"banana" : 3, "total" : 1}})
Conversely, if the banana field already exists, we shouldn't increment the total. But
from the client side, we don't know whether it exists!
There are two ways of dealing with this that are probably becoming familiar: the fast,
inconsistent way, and the slow, consistent way.
The fast way is to chose to either add or not add 1 to total and make our application
aware that it'll need to check the actual total on the client side. We can have an ongoing
batch job that corrects any inconsistencies we end up with.
If our application can take the extra time immediately, we could do a findAndModify
that “locks” the document (setting a “locked” field that other writes will manually
check), return the document, and then issue an update unlocking the document and
updating the fields and total correctly:
> var result = db.runCommand({"findAndModify" : "food",
... "query" : {/* other criteria */, "locked" : false},
... "update" : {"$set" : {"locked" : true}}})
>
> if ("banana" in result.value) {
... db.fruit.update( criteria , {"$set" : {"locked" : false},
... "$inc" : {"banana" : 3}})
... } else {
... // increment total if banana field doesn't exist yet
... db.fruit.update( criteria , {"$set" : {"locked" : false},
... "$inc" : {"banana" : 3, "total" : 1}})
... }
The correct choice depends on your application.
Tip #11: Prefer $-operators to JavaScript
Certain operations cannot be done with $ -operators. For most applications, making a
document self-sufficient will minimize the complexity of the queries that you must do.
However, sometimes you will have to query for something that you cannot express
with $ -operators. In that case, JavaScript can come to your rescue: you can use a
$where clause to execute arbitrary JavaScript as part of your query.
 
Search WWH ::




Custom Search