MongoHQ Blog

MongoDB news, tips and tricks from the MongoDB as a Service Company

Connect to MongoHQ

| Comments

In the first of many posts to simplify connecting to MongoHQ, we’re providing sample code for many programming languages, frameworks and setups (replica sets, slaveOk, etc).

These examples all assume that your MongoHQ connection string is set in an environment variable MONGOHQ_URL, like this:

export MONGOHQ_URL=mongodb://user:pass@server.mongohq.com/db_name

If you use any of our PaaS providers this environment variable should already be set when you choose the MongoHQ add-on. Or you can set it yourself using whatever mechanism the Paas allows. For example, in Heroku:

heroku config:add MONGOHQ_URL=mongodb://...

Today I’ll roll out PHP, two NodeJS (JS and Coffee), and Ruby snippets. In every case we use the basic driver to connect (no frameworks like CakePHP or Mongoid–those will come later).

PHP Connection to MongoHQ

This originally began as a Gist from Larry Hitchon of AppFog. I fixed it up a bit and made it MongoHQ-centric. It’s a pretty straightforward driver. If you don’t have PECL, you should install PECL.

sudo pecl install mongo

NodeJS Connection to MongoHQ (JavaScript)

This code uses the node-mongodb-native driver, though in production you may want something a little less… nesty. Like all good Node packages, you can get it via NPM.

npm install mongodb

NodeJS Connection to MongoHQ (CoffeeScript)

(Side note… I love coffeescript)

Ruby Connection to MongoHQ

We wrap up today by connecting Ruby to MongoHQ. To get started, install the mongo gem. If you want more speed, install the native bson_ext, and if you are in less than Ruby 1.9, you’ll need the json gem. It should go without saying, but you will need RubyGems.

gem install mongo bson_ext json

Part 2 will be Python and Java, and maybe more.

Comments