Handling Errors and Debugging
1. Understanding Error Codes
| Code | Meaning |
|---|---|
| 11000 | DuplicateKey |
| 112 | WriteConflict |
| 50 | ExceededTimeLimit |
| 189 | PrimarySteppedDown |
| 211 | KeyNotFound |
| 251 | NoSuchTransaction |
2. Handling Duplicate Key Errors
| Cause | Mitigation |
|---|---|
| Unique index conflict | Use upsert with retry |
| Bulk write | ordered:false to continue past dup |
3. Handling Write Concern Errors
| Aspect | Detail |
|---|---|
| writeConcernError | Replication didn't ack in time |
| Strategy | Idempotent retry; verify post-state |
4. Debugging with explain() Method
db.orders.find({status:"OPEN"}).explain("executionStats");
5. Using Verbose Logging
| Method | Detail |
|---|---|
| setLogLevel(0–5) | Global verbosity |
| Component-specific | setLogLevel(2, "command") |
6. Checking Server Logs
| Location | Detail |
|---|---|
| systemLog.path | /var/log/mongodb/mongod.log |
| Format (4.4+) | Structured JSON |
7. Using mongod Diagnostic Data
| Aspect | Detail |
|---|---|
| FTDC | Full-Time Diagnostic Data Capture |
| Location | diagnostic.data/ in dbPath |
| Use | Share with MongoDB support |
8. Handling Connection Errors
| Symptom | Cause |
|---|---|
| ServerSelectionTimeout | No reachable primary / wrong RP |
| NetworkTimeout | Firewall, DNS, transient outage |
| Pool exhausted | maxPoolSize too small |
9. Debugging Replication Issues
| Tool | Detail |
|---|---|
| rs.status() | Member states + heartbeat |
| rs.printReplicationInfo() | Oplog window |
| db.adminCommand({getLog:"global"}) | Recent log lines |
10. Using Diagnostic Commands
| Command | Detail |
|---|---|
| hostInfo | OS / hardware info |
| getCmdLineOpts | Effective config |
| whatsmyuri | Connection identity |
11. Understanding Error Handling Best Practices
| Practice | Detail |
|---|---|
| Idempotency | Design ops to be safely retried |
| Retryable writes | Enabled by default in 4.2+ |
| Inspect errorLabels | Use for retry decisions |
| Time-bound | maxTimeMS on every query |