Database Reference
In-Depth Information
:street => "17 W. 18th St.",
:city => "New York",
:state => "NY",
:zip
=> 10011
}
doc['shipping_addresses'].append(new_address)
@users.update({:_id => user_id}, doc)
And here's the targeted approach:
@users.update({:_id => user_id},
{'$push' => {:addresses =>
{:name => "work",
:street => "17 W. 18th St.",
:city => "New York",
:state => "NY",
:zip
=> 10011
}
}
})
The replacement approach, like before, fetches the user document from the server,
modifies it, and then resends it. The update statement here is identical to the one you
used to update the email address. By contrast, the targeted update uses a different
update operator, $push , to push the new address onto the existing addresses array.
Now that you've seen a couple of updates in action, can you think of some reasons
why you might use one method over the other? Which one do you find more intuitive?
Which do you think is better for performance?
Modification by replacement is the more generic approach. Imagine that your
application presents an HTML form for modifying user information. With document
replacement, data from the form post, once validated, can be passed right to
MongoDB; the code to perform the update is the same regardless of which user attri-
butes are modified. So, for instance, if you were going to build a MongoDB object
mapper that needed to generalize updates, then updates by replacement would prob-
ably make for a sensible default. 1
But targeted modifications generally yield better performance. For one thing,
there's no need for the initial round trip to the server to fetch the document to mod-
ify. And just as importantly, the document specifying the update is generally small. If
you're updating via replacement, and your documents average 100 KB in size, then
that's 100 KB sent to the server per update! Contrast that with the way updates are
specified using $set and $push in the preceding examples; the documents specifying
these updates can be less than 100 bytes each, regardless of the size of the document
being modified. For this reason, the use of targeted updates frequently means less
time spent serializing and transmitting data.
1
This is the strategy employed by most MongoDB object mappers, and it's easy to understand why. If users are
given the ability to model entities of arbitrary complexity, then issuing an update via replacement is much
easier than calculating the ideal combination of special update operators to employ.
Search WWH ::




Custom Search