Introducing Dragonfly Cloud! Learn More

Question: What is the MongoDB connection string for a cluster?


MongoDB Atlas and other managed MongoDB services often provide clusters to host your database. Connecting to these clusters requires a specific format of connection string that includes information such as your username, password, cluster address, and database name you wish to connect to. Here's how you can formulate your MongoDB connection string for a cluster:

Standard Connection String Format

The standard connection string format for connecting to a MongoDB cluster looks like this:


Components Explained

  • mongodb+srv:// : This is the prefix to indicate that this string is a MongoDB connection string which uses DNS to retrieve connection information.
  • <username> : Your database username.
  • <password> : Your database password.
  • <cluster-address> : The address of your MongoDB cluster, excluding the 'https://' part.
  • /test : The default database to which you want to connect. You can change 'test' to any database name you wish to use.
  • ?retryWrites=true&w=majority : These are additional options where retryWrites=true enables automatic retry of write operations if they fail, and w=majority ensures write operations require a majority acknowledgment from the replica set.


Let's say your username is user123, your password is pass456, and your cluster address is If you want to connect to a database named myDatabase, your connection string would look like this:


Using the Connection String

To use this string in your application, it typically goes into your database configuration file or section. Here’s how it might look in a Node.js application using the MongoDB native driver:

const { MongoClient } = require('mongodb'); async function main() { const uri = \"mongodb+srv://\"; const client = new MongoClient(uri); try { await client.connect(); console.log(\"Connected correctly to server\"); // perform actions on the collection object } catch (err) { console.error(err); } finally { await client.close(); } } main().catch(console.error);

This example demonstrates how to establish a connection to your MongoDB cluster using the connection string.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.