The MongoDB driver failed to connect to any server within the default 30-second timeout window. This typically indicates network connectivity issues, DNS resolution problems, or server availability issues that prevent the driver from locating and connecting to a MongoDB instance.
The MongoServerSelectionError occurs when the MongoDB driver's server selection mechanism cannot identify a suitable server to execute an operation within the specified serverSelectionTimeoutMS period (default: 30 seconds). Server selection is the process by which a MongoDB driver chooses the appropriate server for any given read or write operation. The driver continuously monitors all known servers in your MongoDB deployment. If no suitable server can be found after exhausting the 30-second timeout, the driver throws this error instead of waiting indefinitely. This error indicates the driver has connectivity issues, cannot resolve the MongoDB hostname, or the MongoDB server(s) are unavailable or unresponsive.
First, confirm your MongoDB server is actually running and listening on the expected port.
# For local MongoDB
mongo --version
mongosh localhost:27017
# For Docker MongoDB
docker ps | grep mongo
# For MongoDB Atlas, check the cluster status in the web interfaceIf MongoDB is not running, start it:
# Local on Linux/Mac
mongod
# Local on Windows
"C:\Program Files\MongoDB\Server\bin\mongod.exe"
# Docker
docker run -d -p 27017:27017 mongoDouble-check your MongoDB connection string for typos, correct hostname, and proper formatting.
// MongoDB Atlas format (recommended)
const uri = "mongodb+srv://username:[email protected]/database?retryWrites=true&w=majority";
// Local MongoDB format
const uri = "mongodb://localhost:27017/mydb";
// Docker MongoDB
const uri = "mongodb://mongo:27017/mydb";Common mistakes:
- Using mongo:// instead of mongodb://
- Missing username or password for MongoDB Atlas
- Typos in hostname or database name
- Not URL-encoding special characters in passwords (use encodeURIComponent() for special chars)
- Missing replicaSet=rs0 parameter for replica sets
Verify network connectivity from your application to the MongoDB server.
# Test DNS resolution
nslookup mongodb.example.com
# or
dig mongodb.example.com
# Test port connectivity
telnet mongodb.example.com 27017
# or (Linux/Mac)
nc -zv mongodb.example.com 27017
# For MongoDB Atlas, verify whitelist IP
# Check MongoDB Atlas dashboard -> Network Access -> IP Whitelist
# Your application's IP must be whitelisted (0.0.0.0/0 allows all IPs, not recommended for production)If connectivity fails:
- Check firewall rules on both client and server
- Verify security groups (AWS) or network policies (Azure, GCP) allow port 27017
- Confirm MongoDB is listening on 0.0.0.0 not just localhost for remote connections
MongoDB Atlas requires explicit IP whitelisting and database users with correct permissions.
1. Navigate to Security → Network Access in the MongoDB Atlas console
2. Add your application's IP address or use 0.0.0.0/0 for testing (restrict to specific IPs in production)
3. Click Security → Database Access and verify:
- Your database user exists
- Password is correct and matches your connection string
- User has appropriate role (at least "readWrite" for the target database)
4. Use the connection string provided by MongoDB Atlas directly
// Example with credentials
const uri = "mongodb+srv://myuser:[email protected]/mydatabase?retryWrites=true&w=majority";By default, MongoDB waits 30 seconds before timing out. For development, you can reduce this for faster error feedback, but this is NOT recommended for production with replica sets.
// Mongoose
mongoose.connect(uri, {
serverSelectionTimeoutMS: 5000, // 5 seconds instead of 30
});
// MongoDB Native Driver
const client = new MongoClient(uri, {
serverSelectionTimeoutMS: 5000,
});
// Prisma
// Adjust the connection URL
// mongodb://localhost:27017?serverSelectionTimeoutMS=5000Note: Only reduce this for development or when using a standalone MongoDB server. For replica sets, keep the default 30 seconds to allow time for failovers.
If using a replica set, ensure proper configuration:
# Connect to MongoDB and check replica set status
mongosh
> rs.status()
# Verify all nodes are healthy (StateStr: PRIMARY, SECONDARY, ARBITER)
# If topology shows "ReplicaSetNoPrimary", the replica set is in an electionFor connection strings with replica sets:
// Must include replicaSet parameter
const uri = "mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0";
// Or for MongoDB Atlas (handles this automatically)
const uri = "mongodb+srv://user:[email protected]/db?retryWrites=true&w=majority";Enable MongoDB driver debug logging to see detailed connection attempts:
// Mongoose
mongoose.set("debug", true);
// MongoDB Native Driver
const { MongoClient, Logger } = require("mongodb");
const logger = new Logger();
logger.setLevel("debug");
// Prisma
// Set environment variable
process.env.DEBUG = "prisma:*";This will show you:
- Hostnames being attempted
- DNS resolution results
- Network errors
- Connection pool status
Intermittent timeouts: If you experience occasional timeouts that resolve themselves, consider: Implementing exponential backoff retry logic in your application, scaling up your MongoDB deployment (upgrade tier or add resources), using connection pooling to reuse connections efficiently, or for serverless environments (AWS Lambda, Azure Functions), keeping the MongoDB client in the global scope to reuse connections across invocations.
Kubernetes/Docker deployments: Service names must be DNS-resolvable. In Docker Compose, use service names from docker-compose.yml directly. In Kubernetes, use the service DNS name (e.g., mongodb-service.default.svc.cluster.local).
Public vs. Private endpoints: MongoDB Atlas supports both. Public endpoints are accessible from anywhere but must whitelist your IP. Private endpoints (AWS PrivateLink, Azure Private Link) only work from within your VPC/VNet but are more secure.
Connection string validation: Test your connection string independently before integrating it into your application using mongosh. This isolates connection issues from application code.
DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work
How to fix "DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work" in MongoDB
MongoServerError: bad auth : authentication failed
How to fix "MongoServerError: bad auth : authentication failed" in MongoDB
CannotCreateIndex: Cannot create index
CannotCreateIndex: Cannot create index
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB