Blog / Rails 4.0 with MongoDB and Mongoid

Rails 4.0 with MongoDB and Mongoid

Chris Oliver

October 13, 2013

If you've never checked out MongoDB before, I'd very much encourage you to. It's a NoSQL document store that makes for a very interesting method of development compared to relational databases. We've been using it a lot lately for prototyping at Efeqdev and have thoroughly enjoyed it. Today we're going to walk through installing it on Ubuntu and setting up Rails with MongoDB and Mongoid to replace ActiveRecord.

First let's install MongoDB from their official repository:

sudo apt-key adv --keyserver --recv 7F0CEB10
sudo echo "deb dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
sudo apt-get -y update
sudo apt-get -y install mongodb-10gen

If you run mongo in your shell you should get an interactive database prompt:

MongoDB shell version: 2.4.6
connecting to: test

Next you're going to need to generate your Rails application with rails new myapp --skip-active-record. The --skip-active-record is important because it doesn't include ActiveRecord in the app that is generated. We need to modify the Gemfile to remove sqlite3 and add Mongoid.

You'll want to delete these lines from your Gemfile:

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

And add these:

gem 'mongoid', '~> 4', github: 'mongoid/mongoid'
gem 'bson_ext'

The mongoid gem that supports Rails 4 hasn't been fully published yet so we're using it directly from their Github repository. Now that these are added you can run bundle to install the gems for your Rails app.

Now we need to generate the Mongoid configuration file that is very much like your config/database.yml that you may be used to with ActiveRecord. We'll create the mongoid file by running the following command:

rails g mongoid:config

This generates config/mongoid.yml which you can take a look at and make any configuration changes as necessary.


And that's all there is to it! While it's much more work than you might expect, I imagine this will become a smoother process in the future once the Rails 4 gem has been released. Be sure to check out Mongoid's documentation for more information on how to use it.

P.S. You might enjoy following me on Twitter.


Want to stay up-to-date with Ruby on Rails?

Join 35,909+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.