Database Reference
In-Depth Information
Deleting such an order, however, presents a problem. One approach is to use two non-atomic
updates:
db
.
orders
.
remove
({
'_id'
:
'1123'
})
db
.
order_items
.
remove
({
'order_id'
:
'11223'
})
Of course, this can leave dangling
order_items
documents around if an exception occurs
between the
remove
calls, and other processes can end up seeing orphaned
order_items
doc-
uments ifthey happen toquerythat collection between ouroperations. Alternatively,wecould
reverse the order:
db
.
order_items
.
remove
({
'order_id'
:
'11223'
})
db
.
orders
.
remove
({
'_id'
:
'1123'
})
Although this guarantees that we won't have “garbage” items in our database, it also intro-
duces the problem of having partially deleted orders, where some or all of the line items are
deleted but the order itself remains. A better approach is to simply embed the order items
within the order document itself:
// "orders" document
{
_id
:
'11223'
,
...
items
:
[
{
sku
:
'...'
, ... },
{
sku
:
'...'
, ... },
...
]
}
Deleting the order, then, is as simple as the single statement:
db
.
orders
.
remove
({
'_id'
:
'1123'
})