MongoDB Connection Strings in Depth

A MongoDB connection string tells the client how to locate a database deployment and provides connection options. Connection strings are often called MongoDB URIs.

Two commonly encountered formats are the standard connection string and the DNS seed-list connection string.

Standard connection string

mongodb://127.0.0.1:27017/learning

This URI specifies a local server, the default port, and learning as the database path.

SRV connection string

mongodb+srv://<username>:<password>@<cluster-host>/learning

The SRV format uses DNS seed-list discovery. It is commonly supplied by managed MongoDB deployments.

Common connection-string components

  • Scheme: mongodb:// or mongodb+srv://.
  • Host: The server address or DNS seed-list hostname.
  • Port: Optional in the URI, depending on the connection format.
  • Database path: The database name associated with the URI.
  • Credentials: Optional username and password information.
  • Query parameters: Additional connection and authentication options.

Authentication source

The database in which a user is authenticated may differ from the database that the application accesses.

For example:

mongodb://courseadmin:<password>@127.0.0.1:27017/learning?authSource=admin

Here, learning is the database in the URI path, while authSource=admin specifies the authentication database.

Special characters in credentials

Characters such as @, :, /, ?, and # have special meanings in URIs. Credentials containing reserved characters must be percent-encoded correctly.

Do not encode the entire connection string as though it were one credential. Encode the relevant username or password components when constructing the URI.

Read and write options

Connection strings can include options related to retryable writes, TLS, authentication, read preference, and write concern. The correct options depend on the deployment and application requirements.

For example, retryWrites=true requests retryable-write behavior when supported. It is not a universal guarantee that every failed operation will be retried successfully.

A write-concern option such as w=majority requests acknowledgment from a majority of voting data-bearing members under the applicable deployment semantics. It affects durability and latency trade-offs and should be understood before changing production settings.

Never expose a connection string in browser code

A database URI containing credentials is a server-side secret. In Next.js, keep it in a server-only environment variable such as MONGODB_URI, and do not prefix it with NEXT_PUBLIC_.

A browser should call an appropriately authenticated backend API rather than connecting directly to a private application database using privileged credentials.

Connection-string components
mongodb://: Standard connection scheme
Commonly used for direct host-and-port connections and standard MongoDB connection configurations.
mongodb+srv://: DNS seed-list scheme
Uses DNS SRV records to discover the deployment's server addresses.
authSource: Authentication database
Specifies the database used to authenticate the provided credentials.
retryWrites: Retryable-write option
Requests retryable writes when the deployment and operation support them.
Read a connection string from a server-side environment variable
const uri = process.env.MONGODB_URI;

if (!uri) {
 throw new Error("MONGODB_URI is not configured");
}

console.log("MongoDB URI is configured:", Boolean(uri));
💡 This Node.js example verifies that the environment variable exists without printing the secret. Do not log the complete URI because it may contain credentials or other sensitive connection information.
Key Takeaways
  • A MongoDB URI identifies the deployment and may contain connection options.
  • The database path and authentication source can be different.
  • Reserved URI characters in credentials must be encoded correctly.
  • Connection options can affect security, consistency, and performance.
  • Database connection strings must remain server-side secrets.
Knowledge Check

In a connection string ending with `/learning?authSource=admin`, what does `authSource=admin` specify?