Databases Reference
In-Depth Information
Installing RDoc documentation for bson-1.0.2...
Installing RDoc documentation for mongo-1.0.2...
Installing the
mongo
gem will also install the
bson
gem on which it depends. The
bson
gem handles all of the BSON encoding and decoding for the driver (for more on
BSON, see
“BSON” on page 179
). The
bson
gem will also make use of C extensions
available in the
bson_ext
gem to improve performance, if that gem has been installed.
For maximum performance, be sure to install
bson_ext
:
$ gem install bson_ext
Building native extensions. This could take a while...
Successfully installed bson_ext-1.0.1
1 gem installed
If
bson_ext
is on the load path, it will be used automatically.
Using the Ruby Driver
To connect to an instance of MongoDB, use the
Mongo::Connection
class. Once we have
an instance of
Mongo::Connection
, we can get an individual database (here we use the
stuffy
database) using bracket notation:
> require 'rubygems'
=> true
> require 'mongo'
=> true
> db = Mongo::Connection.new["stuffy"]
The Ruby driver uses hashes to represent documents. Aside from that, the API is similar
to that of the shell with most method names being the same. (Although the Ruby driver
uses underscore_naming, whereas the shell often uses camelCase.) To insert the docu-
ment
{"x" : 1}
into the
bar
collection and query for the result, we would do the
following:
> db["bar"].insert :x => 1
=> BSON::ObjectID('4c168343e6fb1b106f000001')
> db["bar"].find_one
=> {"_id"=>BSON::ObjectID('4c168343e6fb1b106f000001'), "x"=>1}
There are some important gotchas about documents in Ruby that you need to be
aware of:
• Hashes are ordered in Ruby 1.9, which matches how documents work in
MongoDB. In Ruby 1.8, however, hashes are unordered. The driver provides a
special type,
BSON::OrderedHash
, which must be used instead of a regular hash
whenever key order is important.
• Hashes being saved to MongoDB can have symbols as either keys or values. Hashes
returned from MongoDB will have symbol values wherever they were present in
the input, but any symbol keys will be returned as strings. So,
{:x => :y}
will
become
{"x" => :y}
. This is a side effect of the way documents are represented in
BSON (see
Appendix C
for more on BSON).