Understanding MongoDB Connection Strings

1. Understanding Connection String URI (mongodb://)

PartExampleDescription
schememongodb://Standard URI
userinfouser:pass@URL-encoded credentials
hostsh1:27017,h2:27017Seed list for replica sets
/database/myappDefault database
?options?replicaSet=rs0&tls=trueQuery-style options
mongodb://user:pass@host1:27017,host2:27017/myapp?replicaSet=rs0&authSource=admin&tls=true

2. Connecting to Local Instance

ScenarioURI
Default localhostmongodb://localhost:27017
Implicit (mongosh)mongosh (no URI)
Unix socketmongodb://%2Ftmp%2Fmongodb-27017.sock
Custom portmongodb://localhost:27018

3. Connecting to Remote Server

Use caseURI
Single remotemongodb://db.example.com:27017
Replica set seed listmongodb://h1,h2,h3/?replicaSet=rs0
Atlas (SRV)mongodb+srv://cluster0.abcd.mongodb.net

4. Using Authentication in Connection String

OptionDescription
authSourceDB holding the user (usually admin)
authMechanismSCRAM-SHA-256 (default), MONGODB-X509, PLAIN, GSSAPI, MONGODB-AWS
authMechanismPropertiese.g. SERVICE_NAME:mongodb
mongodb://alice:s%40cret@host/?authSource=admin&authMechanism=SCRAM-SHA-256

5. Setting Database in Connection String

PositionEffect
Before ?Default DB for operations (db in mongosh)
Omittedtest in mongosh; driver-defined elsewhere
authSource (option)Auth DB, may differ from default DB

6. Configuring Connection Pool Options

OptionDefaultPurpose
maxPoolSize100Max open connections per host
minPoolSize0Warm pool size
maxIdleTimeMS0 (∞)Close idle conns after N ms
waitQueueTimeoutMS0Max wait for available conn
maxConnecting2Concurrent new conn attempts

7. Using SRV Connection String (mongodb+srv://)

FeatureDetail
Schememongodb+srv://
HostnameSingle DNS name resolves to multiple via SRV + TXT records
TLSEnabled by default
TXT optionsServer-side defaults (authSource, replicaSet)
mongodb+srv://alice:secret@cluster0.abcd.mongodb.net/myapp?retryWrites=true&w=majority

8. Setting TLS/SSL Options

OptionPurpose
tls=trueEnable TLS
tlsCAFileTrusted CA bundle
tlsCertificateKeyFileClient cert+key (PEM)
tlsCertificateKeyFilePasswordPEM passphrase
tlsAllowInvalidCertificatesSkip cert validation (dev only)
tlsAllowInvalidHostnamesSkip hostname check (dev only)
tlsInsecureCombines the above (dev only)

9. Configuring Connection Timeout

OptionDefaultPurpose
connectTimeoutMS10000TCP+TLS handshake timeout
serverSelectionTimeoutMS30000Max wait to pick a server
heartbeatFrequencyMS10000Topology check interval

10. Setting Socket Timeout

OptionDefaultPurpose
socketTimeoutMS0 (∞)Max time a socket waits for a reply
tcpKeepAlivetrueEnable OS-level keepalive
Warning: Set socketTimeoutMS larger than your slowest expected operation; otherwise long aggregations get killed mid-flight.

11. Handling Connection Pooling Behavior

BehaviorDetail
LazyConnections created on demand up to maxPoolSize
Per hostEach topology host has its own pool
Checkout/CheckinEach operation borrows a conn for its duration
EvictionmaxIdleTimeMS, network errors, server resets
BackpressureOperations wait up to waitQueueTimeoutMS

12. Managing Connection Lifecycle

Driver CallPurpose
MongoClient(uri)Build client (no I/O yet)
client.connect()Open initial monitoring connections
client.db("name")Reference to a DB
client.close()Drain pool, close sockets

Example: Node.js driver lifecycle

import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI, {
  maxPoolSize: 50,
  serverSelectionTimeoutMS: 5000,
});
try {
  await client.connect();
  const users = client.db("app").collection("users");
  const doc = await users.findOne({ email: "a@b.com" });
  console.log(doc);
} finally {
  await client.close();
}