MongoDB performance.

explain

db.coll.find({...}).explain("executionStats")

Look for:

  • IXSCAN (good) vs COLLSCAN (bad).
  • totalDocsExamined close to nReturned.
  • executionTimeMillis.

Profiling

db.setProfilingLevel(1, { slowms: 100 })   // log queries > 100ms
db.system.profile.find().sort({ ts: -1 }).limit(10)

Connection pool

client = MongoClient(uri, maxPoolSize=100)

WiredTiger cache

db.runCommand({ getParameter: 1, wiredTigerEngineRuntimeConfig: 1 })

Default: 50% RAM - 1GB. Tune via:

storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4

currentOp

db.currentOp({ active: true, secs_running: { $gt: 5 } })
db.killOp(opid)

serverStatus

db.serverStatus()

Many useful metrics.

Compact

db.runCommand({ compact: "users" })

For freed-up space after big deletes.

Sharding

For scale beyond single node:

sh.enableSharding("myapp")
sh.shardCollection("myapp.events", { user_id: "hashed" })

Choose shard key:

  • High cardinality.
  • Even distribution.
  • Matches common queries.

{ user_id: "hashed" } or { tenant: 1, _id: 1 }.

Read preference

client.users.with_options(read_preference=ReadPreference.SECONDARY)

Spread reads to replicas. Tolerate stale.

Heap profiling

mongotop 1
mongostat 1

Slow query log

operationProfiling:
  mode: slowOp
  slowOpThresholdMs: 100

Mongos vs mongod

Sharded cluster: app connects to mongos (router).

$lookup performance

{ $lookup: { from: "users", localField: "user_id", foreignField: "_id", as: "user" } }

Slow on huge collections. Mitigations:

  • Denormalize.
  • Index _id and foreignField (already by default for _id).
  • Limit before $lookup.

$group memory

db.coll.aggregate([...], { allowDiskUse: true })

100MB in-memory limit per stage.

Document size

Approaching 16MB → split into multiple docs.

Indexes in RAM

Working set should fit in RAM. If index doesn’t fit → slow.

db.coll.totalIndexSize()

vs WiredTiger cache size.

Hot shards

Distribute writes evenly. Hot shard = uneven shard key.

Avoid full scans

Always check explain on production-shape queries.

Common mistakes

  • No indexes; assuming “Mongo is fast.”
  • Indexes that don’t match query shape.
  • Bulk imports without batched bulk_write.
  • $lookup in tight loop.
  • Forgetting _id is indexed (don’t add another).

Read this next

If you want my Mongo tuning playbook, it’s at rajpoot.dev .


Building something AI-, backend-, or data-heavy and want a second pair of eyes? I do consulting and freelance work — see my projects and ways to reach me at rajpoot.dev .