Database Reference
In-Depth Information
Using Complex Updates
Although using document embedding in your MongoDB schema makes some “transactional”
problems in relational databases easier to handle, there are other cases where we need
something more. For instance, consider our order management system again. Suppose we
wish to store the order total price as well as each line item's price so that we can easily display
the order total without computing it each time. A document might look like the following:
// "orders" document
{
_id : '11223' ,
total : 500.94 ,
...
items : [
{ sku : '123' , price : 55.11 , qty : 2 },
{ sku : '...' , ... },
...
]
}
Now suppose we want to update the quantity of item 123 to 3. A naive approach might be to
read the document from the database, update it in-memory, and then save it back. Unfortu-
nately, this approach introduces race conditions between the loading of the order and saving
it back. What we need is a way to atomically update the document without doing it in client
application code. We can use MongoDB's atomic update operators to perform the same oper-
ation in a single step. We might do so with the following code:
def
def increase_qty ( order_id , sku , price , qty ):
total_update = price * qty
while
while True :
db . orders . update (
{ '_id' : order_id , 'items.sku' : sku },
{ '$inc' : {
'total' : total_update ,
'items.$.qty' : qty } })
In this case, we still have a risk that another operation removed the line item we are interested
in updating (perhaps in another browser window). To account for this case, we must detect
whether our update actually succeeds by checking its return value. If the update failed,
Search WWH ::




Custom Search