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.
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.
mongodb://127.0.0.1:27017
Connects to a MongoDB server on the local computer.
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.
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+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.
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.
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.
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.
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.
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:
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.
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.
Check whether MongoDB is running and listening on the specified host and port.
Verify the username, password, authentication database, and user permissions.
Check the hostname, network connection, firewall rules, server availability, and replica-set configuration.
Check the hostname, DNS configuration, and whether the deployment supports SRV records.
Verify the TLS configuration, certificate validity, and system trust settings. Avoid disabling certificate verification as a permanent workaround.
Check the URI scheme, hostname, port, delimiters, and encoding of special characters in credentials.
Complete the following tasks:
mongodb:// and port 27017.school database.mongodb:// and mongodb+srv://.authSource.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?