9

how can i connect to a mongodb from Ruby code ?

3 Answers 3

15

Firstly, you have to install MongoDb gem:

gem install mongo

Then run code:

require 'rubygems'  # not necessary for Ruby 1.9
require 'mongo'
db = Mongo::Connection.new.db("mydb") # OR
db = Mongo::Connection.new("localhost").db("mydb") # OR
db = Mongo::Connection.new("localhost", 27017).db("mydb")
Sign up to request clarification or add additional context in comments.

Comments

4

Kir's answer is appropriate if you are working only with Ruby. But if you are developing a Rails app, you likely will want to connect to MongoDB with an ORM such as:

Using an ORM will give you the functionality Rails developers are familiar with in ActiveRecord. See a list of MongoDB Clients on http://ruby-toolbox.com/.

Comments

3

Short version: install the Mongo gem, then db = Mongo::Connection.new.db("mydb")

1 Comment

As a side note, these were Google search results #1 and #2 for "mongodb ruby".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.