🍃 MongoDB Intermediate

What is the MongoDB connection string format?

Answer

The MongoDB connection string specifies how to connect to a MongoDB deployment. Two formats: Standard format: mongodb://[username:password@]host[:port][/database][?options]. SRV format (DNS Seedlist): mongodb+srv://[username:password@]host[/database][?options] — used by Atlas; the SRV record provides the host list automatically. Examples: Local: mongodb://localhost:27017/mydb; With auth: mongodb://admin:password@host:27017/admin?authSource=admin; Replica set: mongodb://host1:27017,host2:27017,host3:27017/mydb?replicaSet=myReplicaSet; Atlas: mongodb+srv://username:password@cluster.abc.mongodb.net/mydb. Common connection string options: authSource=admin — database to authenticate against; replicaSet=name — replica set name; w=majority — write concern; readPreference=secondary; maxPoolSize=100 — connection pool size (default 100); connectTimeoutMS=30000 — connection timeout; socketTimeoutMS=360000 — socket timeout; ssl=true / tls=true — enable TLS; retryWrites=true — retry transient write errors (default true since MongoDB 4.0); retryReads=true. Security: never hardcode credentials in connection strings in source code. Use environment variables: process.env.MONGODB_URI. URL-encode special characters in passwords.