Setup MongoDB with Rails

Ademar Tutor | Jan 31, 2015

This a tutorial to help you setup MongoDB as the database for Rails. Let's start with a bit of info on MongoDB.

What is MongoDB?

So what is a NoSQL database? What's difference between a NoSQL database (MongoDB) and SQL database (MySQL, PostgreSQL and etc.)?

There are lots of technical differences, but I'll talk about two key areas: structure and scaling.


NoSQL database allow free-flow operations, however SQL/Relational databases require a structure with defined attributes to hold the data


Both NoSQL and SQL can scale. However, SQL databases were built to scale vertically (increase system resources like adding CPUs or memory to a single computer). NoSQL was built for scaling horizontally (i.e. by creating a cluster of multiple machines; think cloud!).

Now let's start setting MongoDB up.

Step 1

Install MongoDB:

For Linux:

For OS X:

Step 2

We will be using mongoid as the ORM for your Rails application. On your Gemfile, add the following:

gem 'mongoid'

Make sure to remove sqlite gem to avoid conflict.

Step 3

Next step is to tel Rails that you will be using mongoid instead of active_record. On your application.rb file, remove the this line:

require 'rails/all'

And replace it with these lines:

require "active_model/railtie"  
require "action_controller/railtie"  
require "action_mailer/railtie"  
require "action_view/railtie"  
require "sprockets/railtie"  
require "rails/test_unit/railtie"  

Step 4

Remove the following code that still uses active_record.

In development.rb:

config.active_record.migration_error = :page_load

In production.rb:

config.active_record.dump_schema_after_migration = false

In application.rb:

config.active_record.raise_in_transactional_callbacks = true

You can checkout my demo repo for this tutorial:

This is the specific commit on adding mongoid: