Using Mongo in Ruby

Mongo, meet Ruby. Ruby, Mongo. Now that the introductions are out of the way, let's take a look at how we can use MongoDB in our Ruby projects.

**Disclaimer: This article assumes you have Ruby and MongoDB installed on your system.

On a mac, you can install via Homebrew. Open a terminal and enter the following commands:

$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
$ brew install rbenv ruby-build mongodb

Make sure to add rbenv to your shell's profile eval "$(rbenv init -)" You may need to edit ~/.zshrc or ~/.bashrc depending on your setup.

Install a Ruby

$ rbenv install 2.1.0

Reload your freshly installed ruby and set 2.1.0 as the ruby environment.

$ rbenv rehash
$ rbenv local 2.1.0

Install the bundler gem:

$ gem install bundler

Now it's time to build our project. Make a new directory and call it mongo. mkdir mongo Change in to the directory and run bundle init cd mongo && bundle init

Bundle init will create a Gemfile for us. Open the Gemfile and make the following edits, then save:

gem 'sinatra'
gem 'mongo'
gem 'bson_ext'

Back in the terminal, run bundle install

Create a main app file, such as, touch app.rb and make the following edits in the new file:

require 'sinatra'
require 'mongo'
require 'json/ext'

include Mongo

Connect to the mongo database

# Connect to mongoDB
connect = MongoClient.new("localhost", 27017)
set :mongo, connect
set :db, connect.db('test')
set :collection, settings.db['collection']

Insert record

# New record - normally you would use a 'POST' method when interacting with a database
get '/insert' do
  settings.collection.insert({
    name: 'John Doe',
    profession: 'Geologist',
    location: 'United States',
    created_at: Time.now
  })
  'Record inserted.'
end

Find all records

# Find all records
get '/' do
  # Parenthesis on the find method are not needed.
  settings.collection.find().to_a.to_json
end

Update record

# Edit record - normally you would use a 'PUT' method to edit data in a database
get '/update' do
  settings.collection.update({:name => 'John Doe'}, {'$set' => {name: 'John Smith'}})
  'Record updated.'
end

Remove record

# Remove record - normally you would use a 'DELETE' method to remove data from a database
get '/remove' do
  # Copy and paste in the id_string for the record you would like to remove from the index page '/'
  settings.collection.remove(:_id => BSON::ObjectId.from_string('id_string'))
  'Record removed.'
end

Remove collection

# Remove the entire collection
get '/drop' do
  settings.collection.remove()
  'Collection dropped.'
end

Afterwards, make all the necessary saves to your app.rb file. Go back to your terminal, verify you are in the mongo directory and fire up the app.

$ mongod

mongod will start the database. Open a new terminal window, as the mongod command will occupy the previous terminal session until we end that session with Ctrl - c Now, fire up the Ruby app.

$ ruby app.rb

Pay attention to the output for the port number. And open a browser and enter http://localhost:PORT, my port is 4567. My url will look like this, http://localhost:4567.

Play around with the routes and watch the data flow. Congratulations, You're now using mongoDB with Ruby!

This was a basic demonstration on what can be done using the standard Ruby driver for mongoDB. I've created a git repository over on github, were you can download the complete code sample.

Up