How to Connect to a Mongodb from Ruby Code

how can i connect to a mongodb from Ruby code?

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:

  • Mongoid
  • MongoMapper

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/.

mongo - ruby connection problem

This is definitely due to your mongo server not running. Since you're on Ubuntu, try doing a sudo /etc/init.d/mongodb start and then see if your code works.

How to setup mongoid with ruby programming

See the Sinatra tutorial in Mongoid documentation for how to get started with Mongoid without Rails.

Source code is also available.

Ruby Sinatra - connect to mongoDB on mongoHQ failed

I use

uri =  URI.parse(ENV['MONGOHQ_URL'])
@mongo_connection = Mongo::Connection.from_uri( uri )
@mongo_db = @mongo_connection.db(uri.path.gsub(/^\//, ''))
@mongo_db.authenticate(uri.user, uri.password)

You can look up your mongo url using the heroku config --long command

How to get MongoDB version from Ruby code using Mongoid or Mongo Ruby Driver?

You should do the following call (Mongoid 5+):

Mongoid.default_client.command(buildInfo: 1).first[:version]

Or, in earlier versions:

Mongoid.default_session.command(buildinfo: 1)["version"]

(Answer updated according to @yeasayer comment)

Reuse mongodb connection in ruby script

@conn = Mongo::Connection.new("localhost", 27017, :pool_size => 5, :pool_timeout => 5)
db = @conn.db(.....)


Related Topics



Leave a reply



Submit