Database Reference
In-Depth Information
Let's build some documents for your
users
collection. You'll create two documents rep-
resenting two users, smith and jones. Each document, expressed as a Ruby hash, is
assigned to a variable:
smith = {"last_name" => "smith", "age" => 30}
jones = {"last_name" => "jones", "age" => 40}
To s a v e t h e d o c u m e n t s , y o u ' l l p a s s t h e m t o t h e c o l l e c t i o n 's
insert
method. Each call
to
insert
returns a unique
ID
, which you'll store in a variable to simplify later retrieval:
smith_id = @users.insert(smith)
jones_id = @users.insert(jones)
You can verify that the documents have been saved with some simple queries. As usual,
each document's object
ID
will be stored in the
_id
key. So you can query with the
user collection's
find_one
method like so:
@users.find_one({"_id" => smith_id})
@users.find_one({"_id" => jones_id})
If you're running the code in
irb
, the return values for these queries will appear at
the prompt. If the code is being run from a Ruby file, prepend Ruby's
p
method to
print the output to the screen:
p @users.find_one({"_id" => smith_id})
You've successfully inserted two documents from Ruby. Let's now take a closer look at
queries.
3.1.3
Queries and cursors
You just used the driver's
find_one
method to retrieve a single result. It was simple,
but that's because
find_one
hides some of the details of performing queries with
MongoDB. You'll see how this is so by looking at the standard
find
method. Here are
two possible find operations on your data set:
@users.find({"last_name" => "smith"})
@users.find({"age" => {"$gt" => 20}})
It should be clear that the first query searches for all user documents where the
last_name
is smith and that the second query matches all documents where the
age
is
greater than 30. Try entering the second query in
irb
:
irb(main):008:0> @users.find({"age" => {"$gt" => 30}})
=> <#Mongo::Cursor:0x10109e118 ns="tutorial.users"
@selector={"age" => "$gt" => 30}}>
The first thing you'll notice is that the
find
method doesn't return a result set, but
rather a cursor object. Cursors, found in many database systems, return query result
sets in batches for efficiency iteratively. Imagine that your
users
collection contained
a million documents matching your query. Without a cursor, you'd need to return all
those documents at once. Returning such a huge result right away would mean