Lesson 33 of 50 – MongoDB Connection Strings
66%

MongoDB Connection Strings

A MongoDB connection string tells an application how to connect to a MongoDB deployment. It can specify the server address, port, authentication details, database options, and other connection settings.

1. What Is a Connection String?

A connection string is a specially formatted string containing the information required to connect to MongoDB.

Example of a local connection string:

mongodb://127.0.0.1:27017

In this example:

  • mongodb:// identifies the standard MongoDB connection scheme.
  • 127.0.0.1 is the loopback address of the local computer.
  • 27017 is the default MongoDB server port.

This connection string works when a MongoDB server is running locally and listening on the specified address and port.

2. Common Connection String Formats

Local MongoDB Server
mongodb://127.0.0.1:27017

Connects to a MongoDB server on the local computer.

Server on Another Host
mongodb://192.168.1.100:27017

Uses a server address on a local network. The address is only an example; replace it with the actual host.

Connection with Authentication
mongodb://username:password@localhost:27017/?authSource=admin

This example includes credentials and specifies the authentication database. Replace the placeholder username and password with valid credentials.

MongoDB Atlas
mongodb+srv://username:password@cluster.example.mongodb.net/

The mongodb+srv:// scheme uses DNS SRV records to discover the appropriate MongoDB hosts. Use the actual connection string provided by your MongoDB Atlas deployment.

Security: Never publish real database passwords or connection strings containing secrets. Passwords with special characters may need URL encoding.

3. Connect to MongoDB Using Node.js

Install the official MongoDB Node.js driver in your project before using the following code.

npm install mongodb

Create a file named server.js:

const { MongoClient } = require("mongodb");

const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();

        console.log("Connected to MongoDB successfully!");

        const db = client.db("school");

        console.log("Database name:", db.databaseName);

    } catch (error) {
        console.error("Connection failed:", error.message);
    } finally {
        await client.close();
    }
}

main();

Run the program:

node server.js

The program connects to MongoDB, selects the school database, prints its name, and closes the client.

The database does not necessarily need to exist before you call client.db("school"). It is created on the server when data is first written if it does not already exist.

4. Connect to a Specific Database

You can specify a database name in the connection string or select it through the driver API.

Example with a database name in the URI:

mongodb://127.0.0.1:27017/school

Example using Node.js:

const db = client.db("school");

const students = db.collection("students");

The db.collection() method provides access to a collection. It does not by itself insert data or guarantee that the collection already exists.

You can now use students to perform database operations.

5. Use Environment Variables for Connection Strings

Hardcoding credentials directly in application source code is unsafe. Store sensitive connection details in environment variables or a secrets manager.

For example, set an environment variable in Windows Command Prompt:

set MONGODB_URI=mongodb://127.0.0.1:27017

On PowerShell:

$env:MONGODB_URI="mongodb://127.0.0.1:27017"

On Linux or macOS:

export MONGODB_URI="mongodb://127.0.0.1:27017"

Read the variable in Node.js:

const { MongoClient } = require("mongodb");

const uri = process.env.MONGODB_URI;

if (!uri) {
    throw new Error("MONGODB_URI environment variable is missing.");
}

const client = new MongoClient(uri);

Set the variable in the same environment where the Node.js application runs. For production, keep credentials out of source control and restrict access to secrets.

6. Connection String with Authentication

If MongoDB requires authentication, provide valid credentials and the appropriate authentication database.

mongodb://appUser:yourPassword@localhost:27017/school?authSource=admin

In this example:

  • appUser is the database username.
  • yourPassword is a placeholder password.
  • localhost:27017 identifies the server.
  • school is the default database in the URI.
  • authSource=admin identifies the database where the user is authenticated.

The authentication database and the database your application accesses do not have to be the same. Use the authentication database where the user was actually created.

If the username or password contains reserved URI characters, encode those characters as required by the connection-string specification.

7. MongoDB Atlas Connection String

MongoDB Atlas is a hosted MongoDB database service. It provides a connection string for connecting an application to your cluster.

General connection string format:

mongodb+srv://username:password@cluster.example.mongodb.net/school

Typical setup steps:

  1. Create or open an Atlas deployment.
  2. Create a database user with the required permissions.
  3. Configure network access for your application.
  4. Copy the connection string from the Atlas interface.
  5. Replace the placeholders with the appropriate credentials.
  6. Store the completed URI securely in an environment variable.

Use the exact hostname supplied by Atlas. The example hostname above is only a placeholder.

Never make a database publicly accessible to all IP addresses just to solve a connection problem unless that exposure is explicitly justified and secured.

8. Connection Options

MongoDB connection strings can include options that control connection behavior.

Example:

mongodb://127.0.0.1:27017/school?retryWrites=true

Some commonly encountered options include:

  • authSource specifies the authentication database.
  • retryWrites enables retryable writes when supported.
  • tls controls TLS usage where appropriate.
  • connectTimeoutMS specifies a connection timeout in milliseconds.
  • serverSelectionTimeoutMS controls how long the driver waits to select a suitable server.

For example:

mongodb://127.0.0.1:27017/school?serverSelectionTimeoutMS=5000

This sets the server selection timeout to five seconds. Supported options and defaults can differ by driver version and deployment type, so consult the documentation for your chosen driver.

9. Common Connection Errors

Connection Refused

Check whether MongoDB is running and listening on the specified host and port.

Authentication Failed

Verify the username, password, authentication database, and user permissions.

Server Selection Timeout

Check the hostname, network connection, firewall rules, server availability, and replica-set configuration.

DNS Error with mongodb+srv

Check the hostname, DNS configuration, and whether the deployment supports SRV records.

TLS or Certificate Error

Verify the TLS configuration, certificate validity, and system trust settings. Avoid disabling certificate verification as a permanent workaround.

Invalid Connection String

Check the URI scheme, hostname, port, delimiters, and encoding of special characters in credentials.

10. Best Practices

  • Use the correct connection string for the deployment.
  • Store credentials in environment variables or a secrets manager.
  • Use a database user with only the permissions the application needs.
  • Enable TLS when required for remote connections.
  • Do not expose passwords in logs or public repositories.
  • Set suitable connection and server selection timeouts.
  • Reuse a MongoDB client in long-running applications rather than creating one for every request.
  • Close the client when a short-running script finishes.
  • Use the current driver documentation for advanced options.

11. Practical Assignment

Complete the following tasks:

  1. Write a local MongoDB connection string.
  2. Explain the purpose of mongodb:// and port 27017.
  3. Connect a Node.js program to the school database.
  4. Store the connection string in an environment variable.
  5. Write an authenticated connection string using placeholder credentials.
  6. Explain the difference between mongodb:// and mongodb+srv://.
  7. Identify the purpose of authSource.
  8. Describe how to connect an application to MongoDB Atlas.
  9. Explain how to troubleshoot a connection timeout.
  10. List three ways to protect database credentials.

🧠 Quick Quiz

1. What is the purpose of a MongoDB connection string?




2. Which scheme commonly uses DNS SRV records?




3. Why should credentials be kept out of public source code?