Rails + MongoDB Tutorial. Quickstart.

This is a Quickstart Tutorial for Rails + MongoDBRuby 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:
[code type=ruby]
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:
[code type=ruby]
    host: localhost
    database: myapp_dev

    host: localhost
    database: myapp_test

    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”.
[code type=ruby]Mongoid.load!(“config/mongoid.yml”)

Than just add a new Model to your project. For example “User”. That could look like that:
[code type=ruby]
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

That’s it. You just have to include the Mongoid:Document.
[code type=ruby]include Mongoid::Document

And define your fields! Now you can create a new user and save it like that:
[code type=ruby]
user = User.new
user.username = “mike”
user.firstname = “Mike”
user.lastname = “Boby”
user.age = 44

Or make a query like that:
[code type=ruby]user = User.where( username: “mike”)

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

Rails + MongoDB Tutorial. Quickstart.