- MongoDB Drivers and Client Libraries >
- Ruby Language Center
Ruby Language Center¶
This is an overview of the available tools and suggested practices for using Ruby with MongoDB. To skip to more detailed discussion see:
- Ruby Driver Tutorial
- Getting Started with Rails
- Getting Started with Rails 3
- MongoDB Data Modeling and Rails
For a list of external resources, see Ruby External Resources.
Install the bson_ext gem for any performance-critical applications.
The MongoDB Ruby driver is the officially supported Ruby driver for MongoDB. It’s written in pure Ruby, with a recommended C extension for speed. The driver is optimized for simplicity. It can be used on its own, but it also serves as the basis of several object mapping libraries, such as MongoMapper.
Install / Upgrade¶
The Ruby driver is hosted at Rubygems.org. Before installing the driver, make sure you’re using the latest version of rubygems:
gem update --system
Then install the gems:
gem install mongo
To stay on the bleeding edge, you can use the latest source from GitHub. Using your Gemfile:
gem 'mongo', :git => 'git://github.com/mongodb/mongo-ruby-driver.git'
git clone git://github.com/mongodb/mongo-ruby-driver.git cd mongo-ruby-driver/ gem build bson.gemspec; gem install bson-x.x.x.gem gem build bson_ext.gemspec; gem install bson_ext-x.x.x.gem gem build mongo.gemspec; gem install mongo-x.x.x.gem
In versions of the Ruby driver prior to 0.20, the code for serializing to BSON existed in the mongo gem. Now, all BSON serialization is handled by the required bson gem.
gem install bson
For significantly improved performance, install the bson_ext gem. Using compiled C instead of Ruby, this gem speeds up BSON serialization greatly.
gem install bson_ext
If you are running on Windows, you need the Ruby DevKit installed in order to compile the C extensions.
As long it is in Ruby’s load path, bson_ext will be loaded automatically when you require bson.
Beginning with version 0.20, the mongo_ext gem is no longer used.
Because MongoDB is so easy to use, the basic Ruby driver can be the best solution for many applications.
But if you need validations, associations, and other high-level data modeling functions then an Object Document Mapper may be needed.
In the context of a Rails application these provide functionality equivalent to, but distinct from, ActiveRecord. Because MongoDB is a document-based database, these mappers are called Object Document Mappers (ODM) as opposed to Object Relational Mappers (ORM).
Several mappers are available:
- MongoMapper from John Nunemaker
- Mongoid from Durran Jordan
- Mongomatic from Ben Myles
- MongoODM from Carlos Paramio
- MongoModel from Sam Pohlenz
- DriverAPILayer from Alexey Petrushin
All the mappers build on top of the basic Ruby driver and so some knowledge of that is useful, especially if you work with a custom MongoDB configuration.