Database Reference
In-Depth Information
copying all that data into memory, transferring it over the wire, and then deserializing
it on the client side. This would be unnecessarily resource intensive. To prevent this,
queries instantiate a cursor, which is then used to retrieve a result set in manageable
chunks. Of course, this is all opaque to the user; as you request more results from the
cursor, successive calls to MongoDB occur as needed to fill the driver's cursor buffer.
Cursors are explained in more detail in the next section. Returning to the exam-
ple, you'll now fetch the results of the $gt query:
cursor = @users.find({"age" => {"$gt" => 20}})
cursor.each do |doc|
puts doc["last_name"]
end
Here you use Ruby's each iterator, which passes each result to a code block. Here, the
last_name attribute is then printed to the console. If you're not familiar with Ruby
iterators, here's a more language-neutral equivalent:
cursor = @users.find({"age" => {"$gt" => 20}})
while doc = cursor.next
puts doc["last_name"]
end
In this case, you use a simple while loop that iterates over the cursor by assigning suc-
cessive calls to the cursor's next method to a local variable, doc .
The fact that you even have to think about cursors here may come as a surprise
given the shell examples from the previous chapter. But the shell uses cursors the
same way every driver does; the difference is that the shell automatically iterates over
the first 20 cursor results when you call find() . To get the remaining results, you can
continue iterating manually by entering the it command.
3.1.4
Updates and deletes
Recall from the previous chapter that updates require at least two arguments: a query
selector and an update document. Here's a simple example using the Ruby driver:
@users.update({"last_name" => "smith"}, {"$set" => {"city" => "Chicago"}})
This update finds the first user with a last_name of smith and, if found, sets the value
of city to Chicago. This update uses the $set operator.
By default, MongoDB updates apply to a single document only. In this case, even if
you have multiple users with the last name of smith , only one document will be
updated. To apply the update to a particular smith , you'd need to add more condi-
tions to your query selector. But if you actually want to apply the update to all smith
documents, you must issue a multi-update . You can do this by passing :multi => true as
the third argument to the update method:
@users.update({"last_name" => "smith"},
{"$set" => {"city" => "New York"}}, :multi => true)
Search WWH ::




Custom Search