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

text
Error → classify (connect / auth / query / index / cluster) → reproduce in mongosh → fix one layer
LayerWhere to look
ClientDriver error message, URI env vars
Networkping, firewall, Docker network
Servermongod.log, Atlas metrics
Queryexplain("executionStats")

Connection Errors

Connection refused (ECONNREFUSED)

Cause: mongod not running, wrong port, or Docker service down.

Fix:

bash
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 serverSelectionTimeoutMS only 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:

text
mongodb://user:pass%40word@host:27017/mydb?authSource=mydb

Create user in correct database — Security.

User not authorized on collection

Cause: Role lacks readWrite on target database.

Fix:

javascript
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:

javascript
use hello_demo
db.posts.findOne({ _id: ObjectId("507f1f77bcf86cd799439011") })

In PyMongo:

python
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:

javascript
db.posts.getIndexes()

See Indexes.

Performance Errors

Slow queries / timeouts

Cause: COLLSCAN (no index), large documents, missing limit.

Fix:

javascript
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

ErrorLikely fix
DuplicateKeyErrorUnique index — handle or dedupe
OperationFailure code 13Authorization — roles
InvalidId / bad ObjectIdValidate id string before query
Mongoose ValidationErrorSchema 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.

Chapter index?

MongoDB Chapter Index.