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”.
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.
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")