MongoDB Connection String Format
Construct a MongoDB connection string using the mongodb:// URI format. Covers authentication, authSource, replica sets, and common query parameters.
Detailed Explanation
MongoDB URI Format
MongoDB uses the mongodb:// URI scheme (or mongodb+srv:// for SRV-based connections). The format is:
mongodb://[user[:password]@]host[:port][/database][?options]
Authentication Parameters
MongoDB authentication requires three key pieces:
- Username and password in the URI authority section
- authSource — the database used to verify credentials (defaults to
admin) - authMechanism — the authentication method (default is
SCRAM-SHA-256)
Example with explicit auth source:
mongodb://appuser:p4ssw0rd@localhost:27017/myapp?authSource=admin
Replica Set Connections
For replica set clusters, list all members separated by commas:
mongodb://host1:27017,host2:27017,host3:27017/mydb?replicaSet=rs0
The driver will discover the full topology from any reachable member, but listing multiple nodes ensures connectivity even if one is down.
Common Options
| Parameter | Purpose | Example |
|---|---|---|
authSource |
Auth database | admin |
replicaSet |
Replica set name | rs0 |
retryWrites |
Auto-retry writes | true |
w |
Write concern | majority |
readPreference |
Read routing | secondaryPreferred |
maxPoolSize |
Max connections | 50 |
tls |
Enable TLS | true |
Full Production Example
mongodb://appuser:str0ngP%40ss@mongo1.example.com:27017,mongo2.example.com:27017/production?authSource=admin&replicaSet=rs0&retryWrites=true&w=majority&tls=true
This string connects to a two-member replica set with authentication against the admin database, automatic write retries, majority write concern, and TLS encryption.
Use Case
Connecting a Node.js application (using Mongoose or the native MongoDB driver) to a self-hosted replica set or a local single-node development instance.