8eging
Last Updated: February 25, 2016
·
1.247K
· tobiastrelle

Accessing MongoDB w/ Ruby

Accessing MongoDB (one of these hyped NoSQL datastores) is a matter of minutes (assuming you have MongoDB installed and a running mongod process on localhost:27017). First, install the Ruby driver gem:

gem install mongo

Then, start up the Ruby shell:

$ irb
irb(main):001:0> require 'mongo'
=> true
irb(main):002:0> collection = Mongo::Connection.new["rubytest"]["foo"]
...
irb(main):003:0> collection.insert "a" => 1, "b" => "two"
=> BSON::ObjectId('50c97447e8b91809ec000001')

You just added a document to the collection rubytest.foo. Let's check this with the MongoDB shell:

$ mongo rubytest
MongoDB shell version: 2.2.0
connecting to: rubytest
> db.foo.findOne()
{ "_id" : ObjectId("50c97447e8b91809ec000001"), "a" : 1, "b" : "two" }