Handling Errors and Debugging

1. Understanding Error Codes

CodeMeaning
11000DuplicateKey
112WriteConflict
50ExceededTimeLimit
189PrimarySteppedDown
211KeyNotFound
251NoSuchTransaction

2. Handling Duplicate Key Errors

CauseMitigation
Unique index conflictUse upsert with retry
Bulk writeordered:false to continue past dup

3. Handling Write Concern Errors

AspectDetail
writeConcernErrorReplication didn't ack in time
StrategyIdempotent retry; verify post-state

4. Debugging with explain() Method

db.orders.find({status:"OPEN"}).explain("executionStats");

5. Using Verbose Logging

MethodDetail
setLogLevel(0–5)Global verbosity
Component-specificsetLogLevel(2, "command")

6. Checking Server Logs

LocationDetail
systemLog.path/var/log/mongodb/mongod.log
Format (4.4+)Structured JSON

7. Using mongod Diagnostic Data

AspectDetail
FTDCFull-Time Diagnostic Data Capture
Locationdiagnostic.data/ in dbPath
UseShare with MongoDB support

8. Handling Connection Errors

SymptomCause
ServerSelectionTimeoutNo reachable primary / wrong RP
NetworkTimeoutFirewall, DNS, transient outage
Pool exhaustedmaxPoolSize too small

9. Debugging Replication Issues

ToolDetail
rs.status()Member states + heartbeat
rs.printReplicationInfo()Oplog window
db.adminCommand({getLog:"global"})Recent log lines

10. Using Diagnostic Commands

CommandDetail
hostInfoOS / hardware info
getCmdLineOptsEffective config
whatsmyuriConnection identity

11. Understanding Error Handling Best Practices

PracticeDetail
IdempotencyDesign ops to be safely retried
Retryable writesEnabled by default in 4.2+
Inspect errorLabelsUse for retry decisions
Time-boundmaxTimeMS on every query