Understanding MongoDB Connection Strings
1. Understanding Connection String URI (mongodb://)
| Part | Example | Description |
| scheme | mongodb:// | Standard URI |
| userinfo | user:pass@ | URL-encoded credentials |
| hosts | h1:27017,h2:27017 | Seed list for replica sets |
| /database | /myapp | Default database |
| ?options | ?replicaSet=rs0&tls=true | Query-style options |
mongodb://user:pass@host1:27017,host2:27017/myapp?replicaSet=rs0&authSource=admin&tls=true
2. Connecting to Local Instance
| Scenario | URI |
| Default localhost | mongodb://localhost:27017 |
| Implicit (mongosh) | mongosh (no URI) |
| Unix socket | mongodb://%2Ftmp%2Fmongodb-27017.sock |
| Custom port | mongodb://localhost:27018 |
3. Connecting to Remote Server
| Use case | URI |
| Single remote | mongodb://db.example.com:27017 |
| Replica set seed list | mongodb://h1,h2,h3/?replicaSet=rs0 |
| Atlas (SRV) | mongodb+srv://cluster0.abcd.mongodb.net |
4. Using Authentication in Connection String
| Option | Description |
| authSource | DB holding the user (usually admin) |
| authMechanism | SCRAM-SHA-256 (default), MONGODB-X509, PLAIN, GSSAPI, MONGODB-AWS |
| authMechanismProperties | e.g. SERVICE_NAME:mongodb |
mongodb://alice:s%40cret@host/?authSource=admin&authMechanism=SCRAM-SHA-256
5. Setting Database in Connection String
| Position | Effect |
Before ? | Default DB for operations (db in mongosh) |
| Omitted | test in mongosh; driver-defined elsewhere |
| authSource (option) | Auth DB, may differ from default DB |
6. Configuring Connection Pool Options
| Option | Default | Purpose |
| maxPoolSize | 100 | Max open connections per host |
| minPoolSize | 0 | Warm pool size |
| maxIdleTimeMS | 0 (∞) | Close idle conns after N ms |
| waitQueueTimeoutMS | 0 | Max wait for available conn |
| maxConnecting | 2 | Concurrent new conn attempts |
7. Using SRV Connection String (mongodb+srv://)
| Feature | Detail |
| Scheme | mongodb+srv:// |
| Hostname | Single DNS name resolves to multiple via SRV + TXT records |
| TLS | Enabled by default |
| TXT options | Server-side defaults (authSource, replicaSet) |
mongodb+srv://alice:secret@cluster0.abcd.mongodb.net/myapp?retryWrites=true&w=majority
8. Setting TLS/SSL Options
| Option | Purpose |
| tls=true | Enable TLS |
| tlsCAFile | Trusted CA bundle |
| tlsCertificateKeyFile | Client cert+key (PEM) |
| tlsCertificateKeyFilePassword | PEM passphrase |
| tlsAllowInvalidCertificates | Skip cert validation (dev only) |
| tlsAllowInvalidHostnames | Skip hostname check (dev only) |
| tlsInsecure | Combines the above (dev only) |
9. Configuring Connection Timeout
| Option | Default | Purpose |
| connectTimeoutMS | 10000 | TCP+TLS handshake timeout |
| serverSelectionTimeoutMS | 30000 | Max wait to pick a server |
| heartbeatFrequencyMS | 10000 | Topology check interval |
10. Setting Socket Timeout
| Option | Default | Purpose |
| socketTimeoutMS | 0 (∞) | Max time a socket waits for a reply |
| tcpKeepAlive | true | Enable OS-level keepalive |
Warning: Set socketTimeoutMS larger than your slowest expected operation; otherwise long aggregations get killed mid-flight.
11. Handling Connection Pooling Behavior
| Behavior | Detail |
| Lazy | Connections created on demand up to maxPoolSize |
| Per host | Each topology host has its own pool |
| Checkout/Checkin | Each operation borrows a conn for its duration |
| Eviction | maxIdleTimeMS, network errors, server resets |
| Backpressure | Operations wait up to waitQueueTimeoutMS |
12. Managing Connection Lifecycle
| Driver Call | Purpose |
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();
}