Skip to content

Monitoring guide

MongoDB monitoring: metrics that matter

MongoDB slows down when queries miss indexes, the WiredTiger cache is under pressure or secondaries fall behind. serverStatus and the profiler show all three.

4 min read14 sectionsUpdated

On this page

Key points

  • Collection scans (COLLSCAN) are the top cause of slow queries.
  • WiredTiger cache dirty and used percentages reveal memory pressure.
  • Replication lag and oplog window decide failover safety.
  • Connections grow with application instances.

Commands to know

javascript
db.serverStatus().opcounters          // inserts, queries, updates per type (cumulative)
db.serverStatus().connections         // current, available
db.serverStatus().wiredTiger.cache    // bytes in cache, dirty bytes, max configured
rs.printSecondaryReplicationInfo()    // lag per secondary
rs.printReplicationInfo()             // oplog size and time window

db.setProfilingLevel(1, { slowms: 100 })   // log operations slower than 100 ms
db.system.profile.find().sort({ millis: -1 }).limit(5)

What to watch

MetricWorry when
Query latency (p95) per operation typeRising with flat traffic
planSummary COLLSCAN in slow opsAny on large collections
WiredTiger cache used / dirtyUsed near max, dirty above ~20%
Replication lagAbove a few seconds sustained
Oplog windowShorter than your maintenance or recovery time
Connections current / availableAvailable running low

Fixing slow queries

Run .explain("executionStats") on the slow query: compare totalDocsExamined with nReturned. A large ratio means a missing or poor index. Create a compound index that matches the query's equality fields first, then sort fields, then range fields, and confirm the plan uses it (IXSCAN).

Collecting metrics continuously

otel-collector.yamlyaml
receivers:
  mongodb:
    hosts:
      - endpoint: mongo-0:27017
    username: otel_monitor
    password: ${env:MONGO_MONITOR_PASSWORD}
    collection_interval: 60s
exporters:
  otlphttp/vitalrix:
    encoding: json
    metrics_endpoint: ${env:VITALRIX_API}/api/v1/metrics/otlp/v1/metrics
    headers: { x-api-key: ${env:VITALRIX_KEY} }
service:
  pipelines:
    metrics: { receivers: [mongodb], exporters: [otlphttp/vitalrix] }

MongoDB monitoring with VitalRix

Collector metrics arrive over OTLP and can be charted on dashboards and used in alert rules. A TCP check confirms MongoDB accepts connections from the network your app uses, and APM traces show which requests wait on MongoDB and for how long, from the client spans your instrumented services create.

Alerts to start with

  • Replica set member down or not in PRIMARY/SECONDARY state.
  • Replication lag above a few seconds for 5 minutes.
  • Connections available below 20% of the limit.
  • WiredTiger cache dirty above 20% sustained.
  • Slow operations (from the profiler) rising after a deploy.
  • Disk used above 80%.

Index hygiene

Unused indexes cost write performance and memory. db.collection.aggregate([{ $indexStats: {} }]) shows how often each index is used since the last restart; review it periodically and drop indexes nothing uses, after confirming with the teams that own the queries.

The MongoDB metrics that matter

MetricSourceStarting alert
Current vs available connectionsdb.serverStatus().connectionsAvailable below 20% of the total
Operation ratesserverStatus().opcountersA sudden drop or a sustained spike against the usual hour
Replication lagrs.printSecondaryReplicationInfo()Above 30 seconds
WiredTiger cache used and dirtyserverStatus().wiredTiger.cacheDirty above about 20% of the cache, used near its maximum
Queued readers and writersserverStatus().globalLock.currentQueueSustained above zero
Slow operationsDatabase profiler (slowms, 100 ms by default)A rising count after a deploy
Disk useFilesystemAbove 80%
javascript
// log operations slower than 100 ms to system.profile on this database
db.setProfilingLevel(1, { slowms: 100 })
// the slowest recent operations
db.system.profile.find().sort({ millis: -1 }).limit(5)
// is a query using an index? look for COLLSCAN in the winning plan
db.orders.find({ customerId: 42 }).explain('executionStats')

What the incidents look like

  • Collection scans after a new query shape: CPU climbs, the cache churns and every other query slows down. explain() shows COLLSCAN; add the index that matches the filter and sort.
  • The working set outgrows the cache: reads go to disk and latency rises gradually as data grows. Watch cache eviction and page faults.
  • A secondary falls behind during bulk writes, and reads with a secondary read preference return stale data.
  • Connection storms from serverless functions or many application instances, each with its own pool. Cap pool sizes and watch available connections.

Frequently asked questions

Should the profiler always be on?

Level 1 with a sensible slowms is common in production. Level 2 (everything) is too expensive except for short investigations.

How big should the oplog be?

Large enough to cover the longest time a secondary might be offline or resyncing, often a day or more.

Check it now, free

  • MySQL monitoring: key metrics and alerts: Monitor MySQL: connections and threads, query throughput, slow queries, InnoDB buffer pool, replication lag and disk, with the SQL for each check.
  • MongoDB slow queries: how to find and fix them: Find and fix slow MongoDB queries: use the profiler and explain, spot COLLSCAN and in-memory sorts, and follow the ESR rule when designing compound indexes.
  • OpenTelemetry for Django: Trace a Django app with OpenTelemetry: auto-instrument views and the ORM, run under gunicorn safely, trace Celery tasks and export to VitalRix.
  • Next.js performance monitoring: Monitor Next.js apps end to end: Core Web Vitals from real users, server rendering and route handler latency with OpenTelemetry, caching behaviour and errors.
  • Why is my website slow? A step-by-step diagnosis: Diagnose a slow website in order: server, loading, stability and responsiveness. Use real-user data, lab tests and traces to find what to fix first.
  • Node.js performance monitoring: Monitor Node.js apps: event loop delay, heap and garbage collection, request latency per route, outgoing calls and errors.

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.