Connecting to Your Database

Overview

The various methods by which you can connect to your MongoLab-hosted database are described here. We also provide some troubleshooting advice for issues you might encounter while trying to establish a connection.

Finding your database connection info

Follow these steps to obtain the information required to connect to your MongoLab-hosted database(s):

  1. Log in to the MongoLab management portal
  2. Navigate to the MongoDB deployment that you wish to connect to
  3. At the top of the screen, you will see a box with the connection information img-connectstring

The first string is what you would use if you were to connect using the mongo shell and the second string is the standard connection URI string that MongoDB’s standard drivers use.

When connecting to a Rackspace database, if the connection info includes -internal (e.g., http://ds012345-internal.mongolab.com), this means that the connection string maps to an internal Rackspace ServiceNet address which will only be accessible from Rackspace Cloud Server machines running in the same region.

Connection methods

While you can always browse your database using the MongoLab management portal, there are other methods by which to connect to and interact with your MongoDB database. These other methods will be necessary for application integration and many system administration tasks.

mongo interactive shell

The mongo shell is an interactive JavaScript shell interface to MongoDB. After you have installed MongoDB and opened a terminal window, connect to your MongoLab-hosted database with a command similar to the following (replace the necessary values with the information specific to your database, of course):

% mongo ds012345.mongolab.com:56789/dbname -u dbuser -p dbpassword

A successful connection to the mongo shell will look similar to this:

% mongo ds012345.mongolab.com:56789/dbname -u dbuser -p dbpassword
MongoDB shell version: 2.4.6
connecting to: ds012345.mongolab.com:56789/dbname
> 

If you’re having trouble connecting, you may find our troubleshooting guide helpful.

MongoDB driver

In order to provide your application a means to communicate with your MongoDB database, you will need a driver in a language appropriate to your application.

You can go to MongoDB, Inc.’s site to read about the official MongoDB drivers but to help you out, we also provide driver examples in many of the major languages: C#, Java, Node.js, PHP, Python, Ruby, etc.. These examples should run out-of-the-box after you install the appropriate driver(s) and update your MongoDB URI.

MongoLab’s REST API

MongoLab databases can be accessed by your application code in two ways.

The first method - the one we strongly recommend - is to connect using one of the MongoDB drivers (as described above). You do not need to use our API if you use the driver.

The second method, which you should use only if you cannot connect via one of the MongoDB drivers, is via MongoLab’s RESTful data API.

Authenticating to your database

In order to authenticate to your MongoLab database, you need to set it up with the proper credentials.

Managing database users

To add a new database user:

  1. Log in to the MongoLab management portal
  2. From your account’s Home page, navigate to the deployment where you will be adding a user
    • For deployments under the “Servers and Clusters” header, open the desired database after navigating to the deployment
  3. Click the “Users” tab
  4. Click the “Add database user” button to create a new user

You can then use this database user or any of the ones listed to connect to your database.

Managing fully-privileged admin database users

Not available for Sandbox databases

If your MongoLab plan includes a dedicated mongod process and full database server admin privileges, you will be able to manage database users in a special system database in MongoDB called the “admin” database.

To add a new database user in the “admin” database:

  1. Log in to the MongoLab management portal
  2. From your account’s Home page, navigate to the deployment running the admin database you want to access
  3. Open the “admin” database listed in the “System Databases” section
  4. Click the “Users” tab
  5. Click the “Add database user” button to create a new user

Once you are authenticated to your “admin” database, you will be able create more databases and access all the other databases in the server.

Troubleshooting connection issues

What can you do if you are having trouble connecting to your database? Here are some things you can check to rule out possible culprits and find the real source of the problem.

If you’re seeing “Error while trying to show server startup warnings: need to login” at the mongo shell, you could simply be running into a harmless but confusing error message (SERVER-9627).

Check basic network connectivity

If you are having trouble connecting to your MongoLab database, first make sure that you have the proper network access. You can check basic network access and DNS resolution by just pinging your database server. For example:

% ping ds012345.mongolab.com

If the above fails, check your network connection and your DNS settings if you’re using a custom DNS. If your database is on Windows Azure, it’s expected that ping will fail; in this case use netcat to test (see below).

Assuming you can ping the host, the next thing to check is that you can connect to the port. The easiest way to do this is by using nc or netcat. For example:

% nc -w 3 -v ds012345.mongolab.com 12345

You should see output that includes the following:

Connection to ds012345.mongolab.com port 12345 [tcp/*] succeeded!

If this instead gives you an error, check with your network administrator to see if the port is being blocked. If you’re on a Dedicated plan, it’s also possible that custom firewall rules have been configured for your deployment but that the machine you are trying to connect from has not been whitelisted.

Check your database credentials

If everything is fine from a network perspective, the next thing to check is your credentials. The mongo shell is a useful tool when attempting to verify or debug connection details.

We often hear this from users: “When trying to connect to my MongoLab database using the mongo shell I get the following error even though I can log in to the MongoLab management portal (UI) just fine with the same username and password”:

% mongo ds012345.mongolab.com:56789/dbname -u dbuser -p dbpassword
MongoDB shell version: 2.4.6
Enter password: 
connecting to: ds012345.mongolab.com:56789/dbname 
Mon Apr 23 11:41:20 uncaught exception: login failed 
exception: login failed

In this case, it is possible that you’re mistakenly using the username and password that you use to log into your MongoLab account rather than the database user’s username and password. This is a common point of confusion because they are not necessarily the same.

Check your connection timeout setting

If you still cannot connect or having intermittent problems connecting to your database, you should consider adjusting the connection timeout for your driver.

For network latency and security reasons, we strongly recommend that you always connect to your database from the same datacenter that your application is located in.

Still having problems?

If you know you have network access and the correct credentials but you’re still having problems connecting, contact us at support@mongolab.com and be sure to include your connection details (e.g., hostname/server, port, database name).

Known issues and workarounds

I cannot connect to my Rackspace database using the internal address

Rackspace Cloud Servers created before June 3, 2013 might not be able to connect to MongoLab databases due to their expansion of the internal (ServiceNet) IP address range.

For more information, read the Rackspace Knowledge Center article: Updating ServiceNet routes on Cloud Servers created before June 3, 2013

Handling dropped connections on Windows Azure

There is a known issue that the Windows Azure IaaS network enforces an idle timeout of roughly thirteen minutes (empirically arrived at). This can affect persistent connections to our Azure-hosted databases from both inside and outside of Azure. It can also affect connections from an app running in Azure to a MongoLab database (or really any database for that matter) running elsewhere.

We are working with Azure to see if we can’t make things more user-friendly, but in the meantime others have had success by configuring their driver options to work around the issue.

Max connection idle time

The most effective workaround we’ve found in working with Azure and our customers has been to set the max connection idle time below four minutes. The idea is to make the driver recycle idle connections before the firewall forces the issue.

For example, one customer, who is using the C# driver, set MongoDefaults.MaxConnectionIdleTime to one minute and it cleared up their issues.

MongoDefaults.MaxConnectionIdleTime = TimeSpan.FromMinutes(1);

The application code itself didn’t change, but now behind the scenes the driver aggressively recycles idle connections. The result can be seen in the server logs as well: lots of connection churn during idle periods in the app.

There are more details on this approach in one of the related mongo-user threads out there: SocketException using C# driver on azure.

Keepalive

You can also work around the issue by making your connections less idle with some kind of keepalive. This is a little tricky to implement unless your driver supports it out of the box, usually by taking advantage of TCP Keepalive. If you need to roll your own, make sure to grab each idle connection from the pool every couple minutes and issue some simple and cheap command, probably a ping.

Handling disconnects

Disconnects can happen from time to time even without an aggressive firewall setup. Before you get into production you want to be sure to handle them correctly.

First, be sure to enable auto reconnect. How to do so varies from driver to driver, but when the driver detects that an operation failed because the connection was bad turning on auto reconnect tells the driver to attempt to reconnect.

But this doesn’t completely solve the problem. You still have the issue of what to do with the failed operation that triggered the reconnect. Auto reconnect doesn’t automatically retry failed operations. That would be dangerous, especially for writes. So usually an exception is thrown and the app is asked to handle it. Often retrying reads is a no-brainer. But retrying writes should be carefully considered.

The mongo shell session below demonstrates the issue. The mongo shell by default has auto reconnect enabled. I insert a document in a collection named stuff then find all the documents in that collection. I then set a timer for thirty minutes and tried the same find again. It failed, but the shell automatically reconnected and when I immediately retried my find it worked as expected.

% mongo ds012345.mongolab.com:56789/dbname -u dbuser -p dbpassword
MongoDB shell version: 2.4.6
connecting to: ds012345.mongolab.com:56789/dbname
> db.stuff.insert({})
> db.stuff.find() { "_id" : ObjectId("50f9b77c27b2e67041fd2245") }

// wait 30 min 
> db.stuff.find()
Fri Jan 18 13:29:28 Socket recv() errno:60 Operation timed out 192.168.1.111:56789
Fri Jan 18 13:29:28 SocketException: remote: 192.168.1.111:56789 error: 9001 socket exception [1] server [192.168.1.111:56789]
Fri Jan 18 13:29:28 DBClientCursor::init call() failed Fri Jan 18 13:29:28 query failed : dbname.stuff {} to: ds012345.mongolab.com:56789
Error: error doing query: failed
Fri Jan 18 13:29:28 trying reconnect to ds012345.mongolab.com:56789
Fri Jan 18 13:29:28 reconnect ds012345.mongolab.com:56789 ok
> db.stuff.find() { "_id" : ObjectId("50f9b77c27b2e67041fd2245") }