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
Is There a Shorthand If (Without Else) Statement in Ruby on Rails
Best Practice for Limiting the Number of Associations Within a Has_Many Relationship
What Are Factory_Girl Transient Attributes? Why Would I Use One
Ruby on Rails:How to Implement Cancel Button in Form_Tag
Nokogiri Recursively Get All Children
How to Combine a Series of PDFs into One Using Ruby
What's the Efficient Way to Multiply Two Arrays and Get Sum of Multiplied Values in Ruby
Solid Tutorial for Building a Simple Wiki Application in Ruby on Rails
Benefits of Using 'Hash#Fetch' Over 'Hash#[]'
How to Increment an Integer in Ruby
Understand "Current_User" Concept When Creating a Login Session in Ruby
Gmail Threading, Imap and Ruby
How to Join a Table and Count Records in Rails 3
Ruby Imap "Changes" Since Last Check
Anything Speaking Against the Bitnami.Org Ruby/Rails/Redmine Stack