Skip to content
Ruby ODM for MongoDB
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



Version: 0.3.2 2010/03/11

  • 2010-03-10 Slides are out of date, use key instead of attr_accessor with MongoDoc::Document (implementation was way too hackish)
  • 2010-02-23 API is changing significantly
  • 2010-01-23 Tracking MongoDoc with git? READ THIS NOTE1

Quick Start

  • install MongoDB (at least 1.3.2)
  • install the Ruby driver gem install mongo
  • install MongoDoc gem install mongo_doc
  • run an example from this directory ruby -Ilib examples/simple_object.rb


MongoDoc is a simple and easy to use ActiveRecord-like object mapper for mongoDB in Ruby.

MongoDoc is also an extension of the Mongo Ruby Driver making it a snap to get Ruby in and out of mongoDB.

MongoDoc is not ActiveRecord for mongoDB. We do not have callbacks, nor do we have dynamic finders. We do have associations, named scopes, and other features.

MongoDoc is simple, easy-to-use, and fast. And it works with Rails (2.3.x at the moment, 3 soonish?).

MongoDoc is designed to work with document data, if you are looking to map relational data in mongoDB, you will have to look elsewhere.

Ruby objects in mongoDB

Lets just get right into it and save some Ruby objects in mongoDB!

class Contact
  attr_accessor :name, :addresses, :interests

class Address
  attr_accessor :street, :city, :state, :zip, :phone_number

With MongoDoc, instead of saving JSON2, we can save an object directly:

contact = = 'Hashrocket'
contact.interests = ['ruby', 'rails', 'agile']

address =
address.street = '320 First Street North, #712' = 'Jacksonville Beach'
address.state = 'FL' = '32250'
address.phone_number = '877 885 8846'
contact.addresses = [address]

We can query using the powerful mongoDB query syntax, and have it return Ruby objects:

results = collection.find('addresses.state' => 'FL')
hashrocket = results.to_a.find {|contact| == 'Hashrocket'}
puts hashrocket.addresses.first.phone_number

Take a look in the examples directory for more code.

Mapping Documents

MongoDoc provides ActiveRecord-like persistence, associations, named scopes, and validations (from Validatable) as well as a mongoDB query language (from Mongoid). MongoDoc also plays nicely with Rails.

MongoDoc::Document provides all these features as a mixin. A MongoDoc::Document can either be a top-level mongoDB document, or an embedded document contained within a top-level document. Top-level documents are stored in collections named after their class: Contact objects are stored in the ‘contacts’ collection (much like ActiveRecord).

Lets define a Contact document with an Address embedded document:

class Address
  include MongoDoc::Document

  key :street
  key :city
  key :state
  key :zip_code
  key :phone_number

class Contact
  include MongoDoc::Document

  key :name
  key :interests
  has_many :addresses

  named_scope :in_state, lambda {|state| {:where => {'addresses.state' => state}}}

Since a mongoDB document has no fixed schema, we define the composition of a document directly in our classes. Please note we do not specify types! We can also specify has_one or has_many associations.

Building and saving a document is easy:

contact = => 'Hashrocket', :interests => ['ruby', 'rails', 'agile'])
contact.addresses << => '320 1st Street North, #712',
  :city => 'Jacksonville Beach',
  :state => 'FL',
  :zip_code => '32250',
  :phone_number => '877 885 8846')

Now that we have some data, we can query using our named scope:

hashrocket = Contact.in_state('FL').find {|contact| == 'Hashrocket'}

And we can even perform partial updates:

hashrocket.addresses.first.update_attributes(:street => '320 First Street North, #712')


MongoDoc requires mongoDB v1.3.2 or later.

sudo gem install mongo_doc


By default, MongoDoc will read its configuration from ./mongodb.yml. If that file does not exist, it will attempt to connect to a standard MongoDB local server setup and use a database name of "mongodoc".

With Rails

If you are using Rails, MongoDoc will look for its configuration in config/mongodb.yml. If that file does not exist, it will attempt to connect to a standard MongoDB local server setup and use a database name of #{Rails.root.basename}_#{Rails.env}.

Database configuration file

The file is similar to the Rails database.yml file, with environment definitions containing the database configuration attributes. For example:

  name: development
  host: localhost
  port: 27017
    auto_reconnect: true
  name: test
  host: localhost
  port: 27017
    auto_reconnect: true

If you are not using Rails, the default environment is development and you can set the current environment in your code:

MongoDoc::Connection.env = 'test'

You can also change the location of the configuration file:

MongoDoc::Connection.config_path = './config/mongodb.yml'

Programmatically setting the database connection information

Finally, if you do not want to use the database configuration file, you can also set the database name, host, port, options, and strict values directly; for example, to set the database name to stats: = 'stats'


Les Hill, leshill on github


Thanks to Sandro and Durran for some great conversations and some lovely code.

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don’t break it in a
    future version unintentionally.
  • Commit, do not mess with rakefile, version, or history.
    (if you want to have your own version, that is fine but
    bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.


Copyright © 2009 – 2010 Les Hill. See LICENSE for details.

1 Building from HEAD? MongoDoc requires mongoDB v1.3.2 or later. That means you must be using the 1.3.x nightly build as of 2010-01-22 .

2 The Ruby driver exposes an API that understands JSON.

Something went wrong with that request. Please try again.