Database Reference
In-Depth Information
Successfully installed bson-1.4.0
Successfully installed mongo-1.4.0
2 gems installed
Installing ri documentation for bson-1.4.0...
Installing ri documentation for mongo-1.4.0...
Installing RDoc documentation for bson-1.4.0...
Installing RDoc documentation for mongo-1.4.0...
We'll start by connecting to MongoDB. First, make sure that mongod is running. Next,
create a file called connect.rb and enter the following code:
require 'rubygems'
require 'mongo'
@con = Mongo::Connection.new
@db = @con['tutorial']
@users = @db['users']
The first two require statements ensure that you've loaded the driver. The next three
lines instantiate a connection, assign the tutorial database to the @db variable, and
store a reference to the users collection in the @users variable. Save the file and run it:
$ruby connect.rb
If no exceptions are raised, you've successfully connected to MongoDB from Ruby.
That may not seem glamorous, but connecting is the first step in using MongoDB
from any language. Next, you'll use that connection to insert some documents.
3.1.2
Inserting documents in Ruby
All of the MongoDB drivers are designed to use the most natural document represen-
tation for their language. In JavaScript, JSON objects are the obvious choice, since
JSON is a document data structure; in Ruby, the hash data structure makes the most
sense. The native Ruby hash differs from a JSON object only in a couple small ways;
most notably, where JSON separates keys and values with a colon, Ruby uses a hash
rocket ( => ). 2
If you're following along, go ahead and continue adding code to the connect.rb
file. Alternatively, a nice approach is to use Ruby's interactive REPL , irb . You can
launch irb and require connect.rb so that you'll immediately have access to the con-
nection, database, and collection objects initialized therein. You can then run Ruby
code and receive immediate feedback. Here's an example:
$ irb -r connect.rb
irb(main):001:0> id = @users.save({"lastname" => "knuth"})
=> BSON::ObjectId('4c2cfea0238d3b915a000004')
irb(main):002:0> @users.find_one({"_id" => id})
=> {"_id"=>BSON::ObjectId('4c2cfea0238d3b915a000004'), "lastname"=>"knuth"}
2
In Ruby 1.9, you may optionally use a colon as the key-value separator, but we'll be sticking with the hash
rocket in the interest of backward compatibility.
Search WWH ::




Custom Search