Database Reference
In-Depth Information
M ULTIDOCUMENT UPDATES
An update will, by default, only update the first document matched by its query selec-
tor. To update all matching documents, you need to explicitly specify a multi-
document update. In the shell, you can express this by passing true as the fourth
argument of the update method. Here's how you'd add the cheap tags to all docu-
ments in the products collection:
db.products.update({}, {$addToSet: {tags: 'cheap'}}, false, true)
With the Ruby driver (and most other drivers), you can express multidocument
updates more clearly:
@products.update({}, {'$addToSet' => {'tags' => 'cheap'}}, :multi => true)
U PSERTS
It's common to need to insert if an item doesn't exist but update it if it does. You can
handle this normally tricky-to-implement pattern using MongoDB upserts. If the
query selector matches, the update takes place normally. But if no document matches
the query selector, a new document will be inserted. The new document's attributes
will be a logical merging of the query selector and the targeted update document. 7
Here's a simple example of an upsert using the shell:
db.products.update({slug: 'hammer'}, {$addToSet: {tags: 'cheap'}}, true)
And here's an equivalent upsert in Ruby:
@products.update({'slug' => 'hammer'},
{'$addToSet' => {'tags' => 'cheap'}}, :upsert => true)
As you should expect, upserts can can insert or update only one document at a time.
You'll find upserts incredibly valuable when you need to update atomically and when
there's uncertainly about a document's prior existence. For a practical example, see
section 6.2.3, which describes adding products to a cart.
6.4.2
Update operators
MongoDB supports a host of update operators. Here I provide brief examples of each
of them.
S TANDARD UPDATE OPERATORS
This first set of operators is the most generic, and each works with almost any data
type.
$inc
You use the $inc operator to increment or decrement a numeric value:
db.products.update({slug: "shovel"}, {$inc: {review_count: 1}})
db.users.update({username: "moe"}, {$inc: {password_retires: -1})
But you can also use $inc to add or subtract from numbers arbitrarily:
db.readings.update({_id: 324}, {$inc: {temp: 2.7435}})
7
Note that upserts don't work with replacement-style update documents.
Search WWH ::




Custom Search