How to Connect to MongoDB Database Clusters

MongoDB is a source-available cross-platform document-oriented database program for high-volume storage. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.


You can connect to DigitalOcean Managed Databases using command line tools and other third-party clients. This guide explains where to find your MongoDB database’s connection details and how to use them to configure tools and clients.

Retrieve Database Connection Details Using the CLI

How to retrieve database connection details using the DigitalOcean CLI

To retrieve database connection details via the command-line, follow these steps:

  1. Install doctl, the DigitalOcean command-line tool.

  2. Create a personal access token, and save it for use with doctl.

  3. Use the token to grant doctl access to your DigitalOcean account.

                  doctl auth init
                
  4. Finally, retrieve database connection details with doctl databases connection. The basic usage looks like this, but you'll want to read the usage docs for more details:

                  doctl databases connection <database-cluster-id> [flags]
                

Retrieve Database Connection Details Using the API

This API call retrieves the information about your database, including its connection details. The connection details are located in the returned connection JSON object.

How to retrieve database connection details using the DigitalOcean API

To retrieve database connection details using the DigitalOcean API, follow these steps:

  1. Create a personal access token, and save it for use with the API.

  2. Send a GET request to https://api.digitalocean.com/v2/databases/{database_cluster_uuid}

    cURL

    To retrieve database connection details with cURL, call:

    
                    curl -X GET \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $DIGITALOCEAN_TOKEN" \
      "https://api.digitalocean.com/v2/databases/9cc10173-e9ea-4176-9dbc-a4cee4c4ff30"

    Go

    Go developers can use Godo, the official DigitalOcean V2 API client for Go. To retrieve database connection details with Godo, use the following code:

    
                    import (
        "context"
        "os"
    
        "github.com/digitalocean/godo"
    )
    
    func main() {
        token := os.Getenv("DIGITALOCEAN_TOKEN")
    
        client := godo.NewFromToken(token)
        ctx := context.TODO()
    
        cluster, _, err := client.Databases.Get(ctx, "9cc10173-e9ea-4176-9dbc-a4cee4c4ff30")
    }

    Python

    
                    import os
    from pydo import Client
    
    client = Client(token=os.environ.get("DIGITALOCEAN_TOKEN"))
    
    get_resp = client.databases.get_cluster(database_cluster_uuid="a7a89a")

View MongoDB Cluster Connection Details

You use your database’s connection details to configure tools, applications, and resources that connect to the database. To view your database’s connection details, click the name of the cluster on the Databases page to go to its Overview page.

MongoDB Database Overview screen showing connection string

You can view customized connection details based on how you want to connect to the database:

  • Public network and Private network (VPC) options generate connection details based on if you want to connect via the cluster’s public hostname or the cluster’s private hostname. Only other resources in the same VPC network as the cluster can access it using its private hostname.

  • The Database field updates the connection details based on which database you want to connect to.

  • The User field updates the connection details with the user credentials that you would like to connect with.

You can also choose to view the connection details in three different formats:

  • Connection parameters: Database information meant for application configuration, such as Studio 3T.

  • Connection string: A condensed string that you can pass to a client, such as MongoDB Compass.

  • Flags: A complete mongo command that supplies the connection variables as individual flags.

We recommend the flags format because the readability can help if you want to customize the way you connect.

By default, the control panel doesn’t reveal the cluster’s password for security reasons. Click Copy to copy connection details with the password, or click show-password to reveal the password. Once you create a password for a user, you can only view it during the session you created it. We recommend storing your database passwords locally. You can reset a user password at any time.

Note

Cluster hostnames do not resolve using standard dig requests to the hostname in the connection string. MongoDB clusters are hosted on multiple nodes and each has its own hostname. To retrieve the node hostnames of a cluster using dig, you must specify the srv record type in the request and prepend _mongodb._tcp. to the hostname in the connection string like this:

dig srv _mongodb._tcp.<cluster-hostname>

A properly formatted dig request looks like this:

dig srv _mongodb._tcp.db-mongodb-nyc3-73883-4aef1b0f.mongo.ondigitalocean.com

Connect to the Database

You can connect and manage the database using a command line tool or an application that has a graphical user interface (GUI). In this guide, we show you how to connect to the database using the mongo command line tool and the visual database management application, MongoDB Compass.

Any client you use to connect to your cluster must support MongoDB 4.2 or above in order to secure the connection using TLS. Clients that do not support at least MongoDB 4.2 or above will not connect to the cluster.

To connect to MongoDB database clusters using the mongo CLI, you need three things:

Your cluster’s connection details come with a preconfigured connection command that you can copy and paste into a terminal and use to connect to the cluster. The command contains your cluster’s network information and database user credentials.

To connect using this command, click the name of the cluster you want to connect to on the Databases page to go to its Overview page. In the CONNECTION DETAILS section, select Flags from the drop-down menu, then copy and paste the entire command from the control panel into your terminal. An example command looks like this:

mongo "mongodb+srv://doadmin:<replace-with-your-password>@db-mongodb-nyc3-73883-4aef1b0f.mongo.ondigitalocean.com/admin?authSource=admin&replicaSet=db-mongodb-nyc3-73883" --tls

You need to manually edit the connection command to include the user password. We only display user passwords for a short time after user creation. You can reset a user’s password at any time.

A completed connection command looks like this:

mongo "mongodb+srv://doadmin:76U12GRb0HCg4W85@db-mongodb-nyc3-73883-4aef1b0f.mongo.ondigitalocean.com/admin?authSource=admin&replicaSet=db-mongodb-nyc3-73883" --tls
Tip
To save time when formatting the connection command in the future, we recommend storing the cluster’s password as an environment variable on your local machine and then substituting the password value for the variable name in the connection command.

When you connect successfully, your terminal changes to the MongoDB prompt, which displays the name of the database you’re connected to, like db-mongodb-nyc3-73883:>.

Once connected to the database, you can change databases or users, execute queries, and perform other database administration tasks.

To connect to MongoDB database clusters using MongoDB Compass, you need three things:

To connect to your MongoDB database, open MongoDB Compass, then click New Connection in the left navigation menu.

MongoDB Compass New Connection screen with connection string pasted into field

In the Paste your connection string field, paste the connection string provided by DigitalOcean into the field. You may need to manually edit the connection string to include the user password as we only display user passwords for a short time after user creation. You can reset a user’s password at any time.

Once you have entered your connection string, click Connect.

Once connected to the database, you can change databases or users, execute queries, and perform other database administration tasks.

Connect to Standby Nodes as Read-Only Nodes

MongoDB allows you to connect to the primary node and shift your connection’s read traffic to the secondary nodes. This can lighten the workload of your primary node.

To connect to your cluster’s standby nodes and use them as read-only nodes, pass the cluster’s connection string with the readPreference option set to secondary, like this:

mongo "mongodb+srv://doadmin:76U12GRb0HCg4W85@db-mongodb-nyc3-73883-4aef1b0f.mongo.ondigitalocean.com/admin?authSource=admin&replicaSet=db-mongodb-nyc3-73883&readPreference=secondary" --tls

The client connects to the primary node, but directs read queries to the standby nodes.

Note
When directing your queries to the standby nodes, there is a small chance that the standby nodes may be out of sync with the primary node and the latest data may not be available on the standby nodes yet.

If you’re having trouble connecting to the database, you can troubleshoot the connection using our Support page, or you can reference MongoDB’s official documentation.