Getting Started with MongoLab

MongoDB is one of those NoSQL databases that has gathered popularity quickly. Even if you are a little skeptical about the NoSQL movement, some time spent with MongoDB will be a good experience. Especially when you learn that it is an open-source project, and is supported on all of the major operating systems.

It should come as no surprise that a number of PaaS options have appeared for remotely hosting MongoDB. The one I am going to introduce you to in this article is called MongoLab.

The Free Account Options

There is a free account option available. You get 240MB on a shared account, and it can be hosted on Amazon, Rackspace, or Joyent. There is also the option to scale up, should your needs grow. You get a web admin area that shows you an overview of your databases, users, and collections. It also shows you the required connection strings so that you can connect to your database via the MongoDB shell from your own machine.

Get an Account

It only takes seconds to sign up for a free account. Just go here to sign up and you’ll be up and running in no time.

Installing MongoDB

You will need MongoDB installed on your own computer. There are various options you can use, and they are described in detail on the MongoDB website. I recommend that you follow their instructions for creating a data directory. I have installed MongoDB on several different machines, and the process works as detailed every time.

If you use a Mac, I suggest that you download the 64-bit binary release. I have used that method on several different machines and it just works. You can place the folder anywhere you like; I put mine in my home directory to make it easy to call the bin folder from the terminal.

A Word about Drivers

There are MongoDB drivers for all the popular programming languages.

PHP

If you want to work with PHP and MongoDB as detailed in this article, you will need to install the Mongo PHP drivers. There are drivers available for all the main operating systems.

Python

Other programming languages are also supported. If Python is your thing, for example, then you will need to install PyMongo.

Once you have that done, running Python from the shell should allow you to do:

import pymongo

… without getting any errors.

Ruby

There is a Mongo gem for Ruby. First, make sure RubyGems is up to date:

gem update --system

Then you can install the Mongo gem:

gem install mongo

Best advice also suggests that you install the bson_ext gem to optimize performance:

gem install bson_ext

Now you can fire up the Ruby interactive shell and do this:

require 'mongo'

Hit enter, and you should get this response:

=> true

This tells you all is well.

Creating a Database

In the MongoLab web admin panel, you can create a database, which you then connect to and use via your local shell. While logged into your account, click on the “Add” button to create a database:

create a database

You will then be prompted to enter some basic config information:

enter database info

Once that is done, your database will be ready for you to connect to.

Connecting to your MongoLab Account

It might seem strange at first, but to connect to your MongoLab account, you will need MongoDB running on your own machine. Once you have it running, you can then connect to your MongoDB instance on your MongoLab account.

First, start the localhost server from terminal/console:

./mongodb/bin/mongod

This assumes that you have MongoDB installed in your home directory. Then open your MongoLab account in your web browser. You will see the connection information you need at the top of the database window in the web admin area:

MongoLab connection information

I recommend that you use the shell access method since the standard URI method is not yet supported by all drivers.

Open another terminal tab, and instead of the usual ./mongodb/bin/mongo, do this:

./mongodb/bin/mongo dbh23.mongolab.com:27237/my_new_db -u <db-user> -p <db-password>

The exact string you need to use will be the one shown in the web admin section of your account. You can create a user for your database in the web admin area, by clicking on the users tab:

MongoLab creating users

Creating a Collection and Adding Some Records

One of the nice things about MongoDB is that you don’t have to define data structures first. We can just go ahead and start creating records in the shell. We will then be able to view those records in the web admin area of our MongoLab account.

So in the console/terminal session you have running that is connected to your MongoLab database, try the following:

db.task.insert({title:"create a web app that uses Mongodb",status:"in progress",context:"today"})

When you hit return, your record will be saved. What has happened at this point is your collection has been created in the database you are connected to, and your document has been saved to it. With MongoDB, a collection is contextually equivalent to a table, and a document is equivalent to a row in more traditional databases such as MySQL.

Go ahead and add a few more documents in the same manner.

We can then check our documents in the MongoLab web admin area. Click on “Tasks” in the list of collections:

MongoLab collections

And you will see a list of the documents you have created:

MongoLab collections

Using PHP to Access the MongoLab Database and Retrieve Documents

This assumes that you have managed to install the MongoDB PHP drivers for your local system.

The first iteration for our simple app requires us to:

  1. Connect to the MongoLab database
  2. Establish which database we want to work with
  3. Establish which collection we want to work with

We can do that by creating some variables and using the connection string information provided for us by MongoLabs. This time, we’ll use the driver (standard URI) version. We can put our connection attempt in a try/catch block so that the app fails gracefully if we can’t connect for some reason:

<?php
try
{
    $connection = new Mongo('mongodb://<username>:<password>@ds031347.mongolab.com:31347/your_database');
    $database   = $connection->selectDB('your_database');
    $collection = $database->selectCollection('tasks');
}
catch(MongoConnectionException $e)
{
    die("Failed to connect to database ".$e->getMessage());
}

$cursor = $collection->find();

?>

Hopefully, much of this is self explanatory. However, there is some PHP MongoDB class specific stuff in there such as this:

$cursor = $collection->find();

That line of code uses the MongoCursor method to retrieve all the documents in the collection.

Next, we’ll create a HTML document below the existing code, and iterate through the documents to display them on our page:

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Tasks Viewer</title>

    <link type="text/css" rel="stylesheet" href="" />
    <!--[if lt IE 9]>
        <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

</head>
<body>
<h1>My Tasks</h1>

<?php while ($cursor->hasNext()):
    $task = $cursor->getNext(); ?>
    <h2><?= $task['title'] ?></h2>
    <strong>Status:</strong> <?= $task['status']?> <br />
    <strong>Context:</strong> <?= $task['context']?><br />
<?php endwhile;?>
</body>
</html>

Again, if you have spent much time with PHP, this should look fairly simple. We use a while loop to iterate through the returned documents, printing out the data held within them. Notice that the PHP class has hasNext() and getNext() methods specifically for that purpose.

You can read more about the PHP MongoDB class here.

Finally…

Hopefully this article has whetted your appetite enough for you to have a serious look at MongoDB. MongoLab is an excellent service that provides cloud-based access to MongoDB, and runs very quickly indeed. Provided that you get everything installed correctly, you can be coding apps that connect to MongoDB using your favorite technologies in no time.

In the next article, we’ll expand on this simple app, and add the C, U, and D parts of the usual “CRUD” operations we use with other databases.

Leaf image via Shutterstock

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Jared D. Cottrell

    Great article Andy! Thanks for taking the time to walk folks through the initial setup in such detail.

    One note: you shouldn’t have to start a mongod yourself in order to use MongoLab. If you’re having problems getting going without running your own mongod feel free to write us at support@mongolab.com and we’ll help work it through.

    By default most, if not all, MongoDB drivers and clients try to connect to a mongod on localhost:27017. My guess is that if your client errors out unless there’s a mongod running locally it’s because it’s still using the defaults for some reason.