OneBite.Dev - Coding blog in a bite size

How to use mongodb in Rails application

Rails does not support nosql database out of the box. Here is how to use mongodb as database in Rails

Rails has “Active record”. Active record supports relational database management systems (RDBMS) or structured query language (SQL) for Rails. But what about nosql? for example using MongoDB. There’s not out of the box solution on rails documentation.

We will cover how to connect rails application with MongoDB using mongoid .

What is mongoid?

Mongoid is the officially supported object-document mapper (ODM) for MongoDB in Ruby. (Not just Rails!)

Fresh Install

When installing rails as a new project use —skip-active-record option

rails new your_app --skip-active-record

Intall mongoid with Gem

gem install mongoid

Or add this in your Gemfile

gem 'mongoid', '~> 8.0.0'

Feel free to change your desired mongid version.

Run bundle install for this new Gem.


To generate the default config file, run

rails g mongoid: config

It will generate the config file at config/mongoid.yml
Feel free to update hosts or db_name here

Now you can scaffold your apps, for example

bin/rails g scaffold Post title:string body:text

It will generate Post’s models, controllers, etc. (but no db/migration file!)

rails mongodb