Rails + MongoDB Tutorial. Quickstart.

This is a Quickstart Tutorial for Rails + MongoDB. Ruby on Rails and MongoDB, a document based database, is a pretty good fit. It is very easy to integrate MongoDB with Rails. If you want to know how to install MongoDB, check out this article here: Installing MongoDB on Mac OS X Lion. Or this here: Installing MongoDB on Linux.

I assume you are familiar with Ruby on Rails :-)

There are several GEMs to interact with MongoDB. I used the MongoID GEM. That worked pretty good for me. Just add this to your Gemfile:

gem 'bson_ext', '1.6.0'  
gem 'mongo', '1.6.0'
gem 'mongoid', '2.4.6'

And run “bundle install” on your project, to load the GEM from the internet. And add the file mongoid.yml to your config folder:

development:
    host: localhost
    database: myapp_dev

test:
    host: localhost
    database: myapp_test

production:
    host: localhost
    database: myapp_prod

This is the file where you are configuring the access to the database. If your mongodb instance is running locale you don’t need any username or password settings. Now you have to load the mongoid.yml file. You can do that by adding this line to your application.rb inside of the “class Application”.

Mongoid.load!("config/mongoid.yml")

Than just add a new Model to your project. For example “User”. That could look like that:

class User
include Mongoid::Document
include Mongoid::Timestamps
field :username, type: String
field :firstname, type: String
field :llastname, type: String
field :email, type: String
filed :age, type: Integer

end

That’s it. You just have to include the Mongoid:Document.

include Mongoid::Document

And define your fields! Now you can create a new user and save it like that:

user = User.new
user.username = "mike"
user.firstname = "Mike"
user.lastname = "Boby"
user.age = 44
user.save

Or make a query like that:

user = User.where( username: "mike")

Check out the Criteria API for MongoID. That is pretty straight forward. Worked pretty well for me.

7 thoughts on “Rails + MongoDB Tutorial. Quickstart.

  1. It is good to see Mongdb being promoted for Rails apps. We use Mongodb and Mongoid for all of our applications but people do not know how easy it really is.

    Death to rake db:migrate!! LOL

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s