$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[February 09, 2026] MongoDB

MongoDB Wire Protocol: Debugging

MongoDB Wire Protocol: Debugging

────────────────────────────────────────────────────────

MongoDB Wire Protocol: Debugging

Tip: mongosh for Debugging

mongosh --host localhost --port 27017
db.setLogLevel(1, "query")

Enables query logging for debugging.

Gotcha: Connection Pooling

The PHP MongoDB driver maintains a connection pool. Don't create new clients per request.

Tip: Server Selection Timeout

$client = new MongoDB\Client('mongodb://localhost', [
    'serverSelectionTimeoutMS' => 3000,
]);

Controls how long to wait for a server to become available.

Gotcha: Slow Query Log

db.setProfilingLevel(1, { slowms: 100 });

Logs queries taking more than 100ms.

Tip: explain() in PHP

$cursor = $collection->find(['title' => 'Test']);
$cursor->explain('executionStats');

Shows query execution plan from PHP.

Gotcha: BSON Size Limit

Each BSON document is limited to 16MB. This applies to query results too.

Tip: Embed or Reference? The 80/20 Rule

If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.

Tip: Index Your Query Patterns, Not All Fields

Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.

Gotcha: No Transaction Rollback for Index Builds

Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.

Senior Insight

Understanding MongoDB's wire protocol helped me debug a persistent connection issue. MongoDB uses a simple message-based protocol over TCP. Each operation sends a message and waits for a response. Read operations use OP_QUERY (deprecated in favor of OP_MSG in 3.6). I've used this knowledge to diagnose connection pool exhaustion and socket timeout issues that were invisible at the application level. Wireshark with MongoDB protocol decoding is invaluable for deep debugging.

Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)

────────────────────────────────────────────────────────
<-- back to posts