Database Reference
In-Depth Information
You may justifiably ask whether this system is robust enough for production. This
question can't be answered easily without knowing more particulars, but what can be
stated assuredly is that MongoDB provides enough features to permit a usable solu-
tion when you need transaction-like behavior. Granted, no one should be building a
banking system on MongoDB. But if some sort of transactional behavior is required,
it's reasonable to consider MongoDB for the task, especially when you want to run the
application entirely on one database.
6.4
Nuts and bolts: MongoDB updates and deletes
To r e a l l y u n d e r s t an d u p d a t e s i n M o n g o D B , y o u n e e d a h o li s ti c u n d e r s t a n d in g o f
MongoDB's document model and query language, and the examples in the preceding
sections are great for helping with that. But here, as in all of this topic's nuts-and-bolts
sections, we get down to brass tacks. This mostly involves brief summaries of each fea-
ture of the MongoDB update interface, but I also include several notes on perfor-
mance. For brevity's sake, all of the upcoming examples will be in JavaScript.
6.4.1
Update types and options
MongoDB supports both targeted updates and updates via replacement. The former
are defined by the use of one or more update operators; the latter by a document that
will be used to replace the document matched by the update's query selector.
Syntax note: updates versus queries
Users new to MongoDB sometimes have difficulty distinguishing between the update
and query syntaxes. Targeted updates, at least, always begin with the update opera-
tor, and this operator is almost always a verb-like construct. Take the $addToSet
operator, for example:
db.products.update({}, {$addToSet: {tags: 'green'}})
If you add a query selector to this update, note that the query operator is semanti-
cally adjectival and comes after the field name to query on:
db.products.update({'price' => {$lte => 10}},
{$addToSet: {tags: 'cheap'}})
Basically, update operators are prefix whereas query operators are usually infix.
Note that an update will fail if the update document is ambiguous. Here, we've com-
bined an update operator, $addToSet , with replacement-style semantics, {name:
"Pitchfork"} :
db.products.update({}, {name: "Pitchfork", $addToSet: {tags: 'cheap'}})
If your intention is to change the document's name, you must use the $set operator:
db.products.update({},
{$set: {name: "Pitchfork"}, $addToSet: {tags: 'cheap'}})
 
Search WWH ::




Custom Search