Database Reference
In-Depth Information
technique described earlier, but it's probably easier to ensure that all updates in this
case are targeted.
6.2.3
Orders
The atomicity and efficiency of updates that you saw in reviews can also be applied to
orders. Specifically, you're going to see how to implement an Add to Cart function
using a targeted update. This is a two-step process. First, you construct the product
document that you'll be storing in the order's line-item array. Then you issue a tar-
geted update, indicating that this is to be an
upsert
—an update that will insert a new
document if the document to be updated doesn't exist. (I'll describe upserts in detail
in the next section.) The upsert will create a new order object if it doesn't yet exist,
seamlessly handling both initial and subsequent additions to the shopping cart.
3
Let's begin by constructing a sample document to add to the cart:
cart_item = {
_id: ObjectId("4c4b1476238d3b4dd5003981"),
slug: "wheel-barrow-9092",
sku: "9092",
name: "Extra Large Wheel Barrow",
pricing: {
retail: 589700,
sale:
489700
}
}
You'll most likely build this document by querying the
products
collection and then
extracting whichever fields need to be preserved as a line item. The product's
_id
,
sku
,
slug
,
name
, and
price
fields should suffice.
4
With the cart item document, you
can then upsert into the orders collection:
selector = {user_id: ObjectId("4c4b1476238d3b4dd5000001"),
state: 'CART',
'line_items.id':
{'$ne': ObjectId("4c4b1476238d3b4dd5003981")}
}
update = {'$push': {'line_items': cart_item}}
db.orders.update(selector, update, true, false)
To m a k e t h e c o d e m o r e c l e a r, I ' m c o n s t r u c t i n g t h e q u e r y s e l e c t o r a n d t h e u p d a t e d o c -
ument separately. The update document pushes the cart item document onto the
array of line items. As the query selector indicates, this update won't succeed unless
this particular item doesn't yet exist in that array. Of course, the first time a user
3
I'm using the terms
shopping cart
and
order
interchangeably because they're both represented using the same
document. They're formally differentiated only by the document's
state
field (a document with a state of
CART
is a shopping cart).
4
In a real e-commerce application, you'll want to verify that the price has not changed at checkout time.