MongoDB Troubleshooting
Introduction
MongoDB errors often trace to connection strings, auth, missing indexes, or replica set configuration—not mysterious engine bugs. This chapter maps common symptoms to fixes and links back to the chapters where each topic is taught.
Prerequisites
- You have run MongoDB locally or on Atlas — Installation
- Basic terminal and log reading
Diagnostic Flow
Error → classify (connect / auth / query / index / cluster) → reproduce in mongosh → fix one layer| Layer | Where to look |
|---|---|
| Client | Driver error message, URI env vars |
| Network | ping, firewall, Docker network |
| Server | mongod.log, Atlas metrics |
| Query | explain("executionStats") |
Connection Errors
Connection refused (ECONNREFUSED)
Cause: mongod not running, wrong port, or Docker service down.
Fix:
docker compose ps
mongosh "mongodb://127.0.0.1:27017" --eval "db.adminCommand('ping')"See Installation and Docker.
ServerSelectionTimeoutError (PyMongo)
Cause: Host unreachable, wrong URI, Atlas IP not whitelisted, VPN blocking.
Fix:
- Verify
MONGODB_URI - Atlas: Network Access → add client IP
- Increase
serverSelectionTimeoutMSonly after fixing network—not as a permanent bandaid
See Atlas and PyMongo Basics.
Remote cannot connect; local works
Cause: bindIp: 127.0.0.1 in mongod.conf.
Fix: Bind appropriate interfaces or connect through Docker network hostname mongo.
Authentication Errors
Authentication failed
Cause: Wrong user/password, wrong authSource, special characters in password not URL-encoded.
Fix:
mongodb://user:pass%40word@host:27017/mydb?authSource=mydbCreate user in correct database — Security.
User not authorized on collection
Cause: Role lacks readWrite on target database.
Fix:
db.grantRolesToUser("app_user", [{ role: "readWrite", db: "hello_demo" }])Query and Data Errors
Query returns nothing
Cause: Wrong database name, string _id without ObjectId, typo in field name.
Fix:
use hello_demo
db.posts.findOne({ _id: ObjectId("507f1f77bcf86cd799439011") })In PyMongo:
from bson import ObjectId
coll.find_one({"_id": ObjectId(post_id)})See BSON.
E11000 duplicate key error
Cause: Unique index violation (e.g. duplicate slug).
Fix: Handle in app (409 Conflict) or fix data:
db.posts.getIndexes()See Indexes.
Performance Errors
Slow queries / timeouts
Cause: COLLSCAN (no index), large documents, missing limit.
Fix:
db.posts.find({ published: true }).sort({ createdAt: -1 }).explain("executionStats")Add index matching filter + sort — Indexes.
Memory pressure / WiredTiger cache full
Cause: Too many indexes, working set larger than RAM, huge aggregations.
Fix: Project fewer fields, paginate, review index sprawl — Performance.
Transaction and Replica Set Errors
Transaction numbers are only allowed on a replica set member
Cause: Standalone mongod without replica set.
Fix: Init replica set (even single-node for dev) — Transactions, Replica Sets.
Not primary / read concern errors
Cause: Writing to secondary, election in progress, stale topology.
Fix: Use primary for writes; check rs.status().
Docker-Specific
Data gone after container remove
Cause: No named volume for /data/db.
Fix: Declare volumes: mongo_data: — Docker chapter.
Cannot connect from host to mongo:27017
Cause: Using Docker service name from host machine instead of 127.0.0.1.
Fix: From host use published port; from api container use mongo.
Driver-Specific Quick Reference
| Error | Likely fix |
|---|---|
DuplicateKeyError | Unique index — handle or dedupe |
OperationFailure code 13 | Authorization — roles |
InvalidId / bad ObjectId | Validate id string before query |
Mongoose ValidationError | Schema vs payload mismatch |
FAQ
mongosh works but app fails?
Compare exact URI, env loading, and authSource. Shell may use different defaults.
Atlas cluster paused?
M0 free tier pauses after inactivity—resume in Atlas UI.
Collation / case-sensitive slug clash?
Use unique index with collation or normalize slug in app.
Still stuck?
Enable driver debug logging, capture one failing command in mongosh, and compare results.