Connecting to Your Database


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 drivers and client libraries use.

Managing database users

To add a new database user (to create an admin database user, skip these steps and read the sub-section below):

  1. Log in to the MongoLab management portal
  2. From your account’s Home page, navigate to the deployment
    • If applicable, then navigate to the database for which you will be adding a user
  3. Click the “Users” tab
  4. Click the “Add database user” button to create a new user

You can then use this database user to connect to your database.

Creating an admin database user

Available for Dedicated plans only

If your MongoLab plan includes a dedicated mongod process and full database server admin privileges, you will be able to manage fully privileged 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
  3. Navigate to 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, access all the other databases in the deployment, etc.

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 the version of MongoDB that matches the version that your MongoLab-hosted deployment is running on, open a terminal window. In the 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 -u dbuser -p dbpassword

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

% mongo -u dbuser -p dbpassword
MongoDB shell version: 2.6.4
connecting to:

You may find our troubleshooting guide helpful if you continue to experience problems trying to connect to your deployment via the mongo shell.

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 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.

You may find our troubleshooting guide helpful if you continue to experience problems trying to connect to your deployment using a compatible driver.

MongoLab Data 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. In fact, using a driver provides better performance, better security, and more functionality.

The second method is to connect via MongoLab’s RESTful Data API. Use this method only if you cannot connect using a MongoDB driver.

Replica set connections and high availability

MongoDB replica sets provide high availability using automatic failover. Failover allows a secondary member to become primary if the primary is unavailable.

Our Shared and Dedicated Cluster plans are MongoDB replica sets with at least two data-bearing nodes that have been configured to be electable (i.e., eligible to be primary). This configuration allows for redundancy and increased data availability which are critical for most production applications.

An application will gracefully handle failover events if it has been properly configured to use a replica set connection.

How to make a replica set connection

Your connection configuration should include the address of every primary-eligible member (in any order) of your replica set.

If you follow the steps to find your database connection information, you’ll notice that your replica set connection URI has a list of server addresses (hostname/port pairs) and looks similar to the following example:


Each hostname/port pair corresponds to one of the data-bearing members in your replica set. Drivers will use this list as a seed list to connect to the replica set. Once connected, drivers will auto-discover the replica set’s member configuration.

For most drivers, passing in the replica set connection URI is sufficient. If you’re using an unofficial MongoDB library, you should consult the library’s documentation to ensure that it supports replica set connections and configure your connection code accordingly.

What to expect during failover

When a primary becomes unavailable, the failover process initiates and the replica set will hold an election to select a new primary. Typically, this process lasts about 10 seconds, but it can range anywhere between 5-30 seconds. During failover, your application will encounter errors as it attempts to write.

To help you understand and prepare for failover, we provide a publicly-accessible MongoDB replica set called flip-flop that fails over every 60 seconds. This tool makes it easy to visualize the replica set election process and is available so that you can practice writing client driver connection using a test application.

Testing auto-failover

We highly recommend testing to ensure that your application can survive replica set elections and failover without the need for manual intervention. One easy way to conduct this test is to manually initiate a failover for your cluster.

If you experience any issues related to your replica set connection, contact us at with your exact driver version and your connection configuration settings with your database password masked for security (we do not need to know the password to assist).

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, also 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

If the test above fails, check your network connection and your DNS settings if you’re using a custom DNS. If your database is on 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 12345

You should see output that includes the following:

Connection to 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 -u dbuser -p dbpassword
MongoDB shell version: 2.6.4
Enter password: 
connecting to: 
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 shell/driver version compatibility

If everything is fine from a network perspective and the database credentials you’re using are correct, the next thing to ensure is that you are connecting using a compatible method.

For example, the release of MongoDB 3.0 included support for the SCRAM-SHA-1 challenge-response user authentication mechanism, which changed how MongoDB uses and stores user credentials. Applications connecting to database deployments running MongoDB 3.0 must do so using drivers which also support SCRAM-SHA-1.

Mongo shell

If you are having trouble connecting (and authenticating) to your MongoLab database using the mongo shell, check to see that you are using a shell version that matches the release version of your MongoLab-hosted deployment. For example, if your database is running MongoDB 3.0.x, then your shell version should also be 3.0.x.


If you are having trouble connecting (and authenticating) to your MongoLab database using a MongoDB driver, ensure that the version of the driver you’re using is compatible with the version of your MongoLab database by checking MongoDB’s Driver Compatibility Tables.

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 and you’re still having problems connecting, contact us at and be sure to include your connection details (e.g., hostname/server, port, database name).

Known issues and workarounds

Handling dropped connections on Azure

There is a known issue that the Azure IaaS network enforces an idle timeout of four (4) minutes. 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, however, 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 the issue.

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.

Additional details on this approach can be found in one of the related MongoDB user forums on the Internet such as: SocketException using C# driver on Azure.


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.

However, 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. 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. In this example, a document was inserted into a collection named stuff, then a find was issued for all the documents in that collection. Thirty minutes later, the same query was tried again. The query failed, but the shell automatically reconnected and upon another re-try, the query worked as expected.

% mongo -u dbuser -p dbpassword
MongoDB shell version: 2.6.4
connecting to:
> 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
Fri Jan 18 13:29:28 SocketException: remote: error: 9001 socket exception [1] server []
Fri Jan 18 13:29:28 DBClientCursor::init call() failed Fri Jan 18 13:29:28 query failed : dbname.stuff {} to:
Error: error doing query: failed
Fri Jan 18 13:29:28 trying reconnect to
Fri Jan 18 13:29:28 reconnect ok
> db.stuff.find() { "_id" : ObjectId("50f9b77c27b2e67041fd2245") }