A MongoDB connection string is a URI that provides the necessary information for your application to connect to a MongoDB database. The format of the connection string can vary based on your setup (local or cloud, authentication, etc.). Here’s a breakdown of the common formats and examples.
Basic Format
The basic format for a MongoDB connection string is:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
Components
mongodb://: The protocol used to connect to MongoDB.username:password@: Optional credentials for authentication.host1: The hostname or IP address of the MongoDB server (can be multiple hosts for replica sets).:port1: Optional port number (default is 27017)./defaultauthdb: Optional database for authentication.?options: Optional parameters (e.g., connection timeouts, replica set names).
Examples
1. Local MongoDB Instance
For a local instance with no authentication:
mongodb://localhost:27017/mydatabase
2. With Authentication
For a connection with authentication:
mongodb://username:password@localhost:27017/mydatabase
3. Using a Replica Set
If you’re connecting to a replica set:
mongodb://host1:27017,host2:27017,host3:27017/mydatabase?replicaSet=myReplicaSet
4. MongoDB Atlas Connection String
For connecting to a MongoDB Atlas cluster, you can find the connection string in the Atlas UI, which typically looks like:
mongodb+srv://username:password@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority
mongodb+srv://: Indicates a DNS Seed List connection.retryWrites=true: Enables retryable writes.w=majority: Ensures writes are acknowledged by the majority of nodes.
Connection Options
You can customize your connection with options like:
retryWrites=true: Enables automatic retry on certain write operations.w=1: Sets write concern.readPreference=secondary: Routes read operations to secondary members in a replica set.
Example in Code
Here’s how you might use a connection string in a Node.js application:
const { MongoClient } = require('mongodb');
const uri = “mongodb://username:password@localhost:27017/mydatabase”;
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
console.log(“Connected successfully to MongoDB”);
} finally {
await client.close();
}
}
run().catch(console.error);
Summary
The connection string is essential for establishing a connection to your MongoDB database.
