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

Answer

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:

mongodb+srv://<username>:<password>@<cluster-address>/test?retryWrites=true&w=majority

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.

Example

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

mongodb+srv://user123:pass456@cluster0.example.mongodb.net/myDatabase?retryWrites=true&w=majority

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://user123:pass456@cluster0.example.mongodb.net/myDatabase?retryWrites=true&w=majority\"; 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?

Start building today

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