Database Reference
In-Depth Information
the power of the findAndModify command. After numerous examples, there will be a
section devoted to the nuts and bolts of each update operator. I'll also include some
notes on concurrency and optimization, and then end with a brief but important sum-
mary of how to delete data in MongoDB.
By the end of the chapter, you'll have been exposed to the full range of
MongoDB's CRUD operations, and you'll be well on your way to designing applica-
tions that best take advantage of MongoDB's interface and data model.
6.1
A brief tour of document updates
If you need to update a document in MongoDB, you have two ways of going about it.
You can either replace the document altogether or you can use some combination of
update operators to modify specific fields within the document. As a way of setting the
stage for the more detailed examples to come, I'll begin this chapter with a simple
demonstration of these two techniques. I'll then provide some reasons for preferring
one over the other.
To start, recall the sample user document. The document includes a user's first and
last names, email address, and shipping addresses. You'll undoubtedly need to update
an email address from time to time, so let's begin with that. To replace the document
altogether, we first query for the document, then modify it on the client side, and then
issue the update with the modified document. Here's how that looks in Ruby:
user_id = BSON::ObjectId("4c4b1476238d3b4dd5000001")
doc
= @users.find_one({:_id => user_id})
doc['email'] = 'mongodb-user@10gen.com'
@users.update({:_id => user_id}, doc, :safe => true)
With the user's _id at hand, you first query for the document. Next you modify the doc-
ument locally, in this case changing the email attribute. Then you pass the modified
document to the update method. The final line says, “Find the document in the users
collection with the given _id , and replace that document with the one I've provided.”
That's how you modify by replacement; now let's look at modification by operator:
@users.update({:_id => user_id},
{'$set' => {:email => 'mongodb-user@10gen.com'}},
:safe => true)
The example uses $set , one of several special update operators, to modify the email
address in a single request to the server. In this case, the update request is much more
targeted: find the given user document and set its email field to mongodb-
user@10gen.com .
How about another example? This time you want to add another shipping address
to the user's list of addresses. Here's how you'd do that as a document replacement:
doc = @users.find_one({:_id => user_id})
new_address = {
:name
=> "work",
Search WWH ::




Custom Search