mongosh Connection Strings (mongodb:// URIs) in CI
A mongodb:// (or mongodb+srv://) URI tells mongosh which host, database, credentials, and options to connect with.
Most CI connection failures are URI problems: a missing authSource, an SRV lookup that does not resolve, or a replica set name mismatch. Getting the string right fixes them.
What it does
A MongoDB connection string encodes the host(s), the default database, credentials, and connection options as query parameters. mongosh parses it, resolves hosts (DNS SRV for mongodb+srv://), and applies options like authSource, replicaSet, and tls.
Common usage
mongosh "mongodb://user:pass@localhost:27017/app?authSource=admin"
# replica set, forcing a direct connection to one node
mongosh "mongodb://localhost:27017/app?replicaSet=rs0&directConnection=true"
# Atlas-style SRV record (resolves multiple hosts via DNS)
mongosh "mongodb+srv://user:pass@cluster0.example.mongodb.net/app"Options
| URI option | What it does |
|---|---|
| authSource=admin | Database that holds the user (often admin, not the app db) |
| replicaSet=rs0 | Name of the replica set to connect to |
| directConnection=true | Connect to one node without replica-set discovery |
| tls=true | Use TLS for the connection |
| retryWrites=false | Disable retryable writes (needed on standalone servers) |
| mongodb+srv:// | Resolve hosts and options from a DNS SRV/TXT record |
In CI
When the user was created in the admin database, you must pass authSource=admin even though you connect to the app db; otherwise auth fails against the wrong source. For a single-node container started with --replSet, add directConnection=true so the driver does not hang trying to discover other members.
Common errors in CI
"MongoServerError: Authentication failed" most often means a wrong authSource, not a wrong password. "querySrv ENOTFOUND" or "no addresses found" on a mongodb+srv:// URI means DNS cannot resolve the SRV record from the runner. "MongoServerSelectionError ... getaddrinfo ENOTFOUND" means the host name is wrong; inside a job, a service container is reachable by its label, not localhost.