
MongoDB monitoring is less about collecting every possible metric and more about catching the few failure modes that reliably predict incidents: replication issues, resource saturation, runaway query latency, and unexpected data change. The most effective approach combines control-plane signals (server health and topology) with data-plane checks (queries that validate your application’s assumptions).
This guide walks through what to monitor, why it matters, and how to design alerts that are actionable instead of noisy—using practical thresholds, query patterns, and a few ready-to-adapt examples.
What “good” MongoDB monitoring looks like
Healthy monitoring answers three questions quickly:
- Is the cluster able to serve reads/writes? (availability + replication state)
- Is performance degrading? (latency + slow operations + resource pressure)
- Is the data behaving as expected? (backlogs, spikes, missing events, integrity checks)
Principle: Alert on user impact or high-confidence precursors to user impact, not on every fluctuation.
Core MongoDB monitoring signals (and why they matter)
Below are the signals that most often correlate with real incidents. Some come from MongoDB’s administrative views (for example serverStatus), while others are best validated via application-aware queries.
| Signal | What it indicates | Common alert rule |
|---|---|---|
| Replica set primary/secondary state | Failover, elections, split-brain risk | Primary missing, frequent elections, member not reachable |
| Replication lag | Secondaries falling behind; stale reads; failover risk | Lag > N seconds for M minutes (per member) |
| Write concern / majority commit issues | Writes not being acknowledged as expected | Spike in writeConcernErrors or timeouts |
| Slow queries / slow operations | Index regressions, hot partitions, degraded performance | p95/p99 latency above threshold; count of slow ops exceeds baseline |
| Connections / active clients | Connection storms, pool misconfig, DoS-like behavior | Connections near max; sudden jump vs baseline |
| CPU, memory, disk I/O pressure | Resource saturation driving latency and timeouts | Sustained saturation + correlated latency |
| Disk space / oplog window | Out-of-disk outages; replication breakage | Disk < X% free; oplog window below expected recovery horizon |
| Application data invariants | Business-impacting data drift or backlog | Queued jobs > threshold; missing records; stalled pipeline |
Replica set health: the fastest path to actionable alerts
For most production MongoDB deployments, replication issues are the highest-value alert category because they are tightly tied to availability. Monitor:
- Member state (PRIMARY/SECONDARY/RECOVERING/UNKNOWN)
- Election frequency (frequent elections often mean instability)
- Replication lag (per secondary)
Practical lag alerting
A common mistake is alerting on a single lag spike. Instead, require persistence (for example, lag > 60s for 5–10 minutes) and differentiate by workload: analytics secondaries can tolerate more lag than read-from-secondary services.
In mongosh, you can inspect replica status and compute lag conceptually by comparing timestamps. The snippet below is a simple starting point for a scheduled check (adapt it to your environment and auth model):
// mongosh (conceptual example)
const status = rs.status();
const primary = status.members.find(m => m.stateStr === "PRIMARY");
const primaryOptime = primary.optimeDate;
const lags = status.members
.filter(m => m.stateStr === "SECONDARY")
.map(m => ({
name: m.name,
lagSeconds: Math.max(0, (primaryOptime - m.optimeDate) / 1000)
}));
printjson({ primary: primary.name, lags });
Alert idea: page only when (a) the primary is missing or (b) any secondary lag exceeds your tolerated window for a sustained period. For less critical secondaries, route to a ticket instead of paging.
Performance monitoring: catch regressions before they become outages
Performance problems in MongoDB often come from a few repeatable causes:
- Missing or unused indexes causing collection scans
- Hot keys (a single shard/partition doing most writes)
- Query shape changes after a deploy
- Resource ceilings (CPU, memory, disk I/O)
Slow operations: monitor counts, not just single events
If you can collect slow operation data (via profiling or logs), avoid alerting on one slow query. Instead, alert on rate or percentiles:
- Rate-based: slow ops > 50/min for 10 minutes
- Latency-based: p95 > 200ms for 15 minutes (per endpoint or query pattern)
- Impact-based: slow ops correlated with elevated error rate/timeouts
If you use the MongoDB profiler (with appropriate caution in production), you can query for slow operations. Example (assuming profiling is enabled at a safe level and your environment supports it):
// Find slow ops in the last 15 minutes (example)
use mydb;
db.system.profile.aggregate([
{ $match: {
millis: { $gte: 200 },
ts: { $gte: new Date(Date.now() - 15 * 60 * 1000) }
}},
{ $group: {
_id: "$command.find",
count: { $sum: 1 },
maxMillis: { $max: "$millis" },
avgMillis: { $avg: "$millis" }
}},
{ $sort: { count: -1 } },
{ $limit: 10 }
]);
Alert idea: trigger when the count of slow ops for a specific query shape exceeds a baseline (for example, > 5× typical) rather than using a fixed threshold everywhere.
Capacity and growth: disk, oplog window, and “silent” saturation
Capacity issues rarely appear as a single dramatic metric; they show up as slow creep and then abrupt failure. In MongoDB monitoring, prioritize:
- Disk free space on every node (leave headroom for compaction/maintenance)
- Oplog window (how far back a secondary can fall and still catch up)
- Index and collection growth (unexpected growth can be a bug or abuse)
Query-based growth checks (simple and effective)
Even without deep infra tooling, you can detect suspicious growth patterns with lightweight queries. For example, watch “new documents per interval” for critical collections to catch ingest loops.
// Count new documents created in the last 10 minutes
// Requires a createdAt field indexed for efficiency
const tenMinAgo = new Date(Date.now() - 10 * 60 * 1000);
db.orders.countDocuments({ createdAt: { $gte: tenMinAgo } });
Alert idea: if the count exceeds an expected envelope (for example, > 2× peak) for consecutive intervals, alert. This often catches runaway job replays or duplicate ingestion early.
Data-plane monitoring: alerts your metrics can’t see
Traditional monitoring answers “is MongoDB up?” Data-plane monitoring answers “is the system doing the right thing?” This is where query-based alerts shine, especially for mongodb monitoring in product and analytics teams.
Patterns that work well
- Backlog detection: jobs queued too long, events not processed
- Freshness checks: no new records when you expect constant flow
- Invariant checks: impossible states (negative balances, missing foreign references)
- Anomaly detection: sudden spikes/drops compared to baseline
Example: detect a stuck processing pipeline
Suppose orders move through states: NEW → PAID → FULFILLED. A common incident is a stalled worker where items remain in PAID too long.
// Count orders stuck in PAID for > 30 minutes
const cutoff = new Date(Date.now() - 30 * 60 * 1000);
db.orders.countDocuments({
status: "PAID",
paidAt: { $lte: cutoff }
});
Alert idea: page if the stuck count > 0 for 3 consecutive checks (to avoid transient delays), and include the top few oldest items for fast triage.
Designing low-noise alert rules (the part most teams skip)
Alert fatigue usually comes from two root causes: thresholds set without context, and alerts that don’t imply a clear next action. Use these design rules:
- Prefer multi-signal alerts: latency + error rate is more actionable than CPU alone.
- Require persistence: 3 of 5 checks breached is often better than 1 of 1.
- Separate paging vs ticketing: page for imminent user impact; ticket for trend issues.
- Attach context: include the query, the current value, and a small “what changed” hint.
- Baseline when possible: compare to the last hour/day rather than a fixed threshold.
Suggested severity mapping
| Severity | Example MongoDB condition | Typical response |
|---|---|---|
| P1 (page) | No PRIMARY elected, or majority writes failing | Immediate on-call action |
| P2 (page or urgent) | Replication lag > 5–10 min sustained; p99 latency > SLO | Triage within minutes |
| P3 (ticket) | Disk trending to < 20% free; slow ops rising vs baseline | Plan remediation |
| P4 (info) | Minor fluctuations, single-node transient alerts | Observe, no action |
Security for MongoDB monitoring: keep it read-only and encrypted
Monitoring often needs database access, so treat it like production code:
- Use least-privilege credentials: read-only roles for application collections; limited admin views if required.
- Encrypt connections: TLS everywhere; validate certificates.
- Store secrets safely: use a secret manager and rotate credentials.
- Avoid heavy queries: index your monitoring queries and keep intervals sensible.
For query-based checks, prefer targeted filters on indexed fields (like createdAt, status, or partition keys) to avoid accidental load during peak traffic.
Putting it together: a simple monitoring checklist
- Replica set: primary present, members healthy, elections not frequent, lag bounded
- Performance: latency percentiles, slow op rate, connection trends
- Capacity: disk free space, oplog window, growth anomalies
- Data-plane: freshness, backlogs, invariants, anomaly envelopes
- Alert hygiene: persistence, context, routing, and baseline-based thresholds
Conclusion
Effective mongodb monitoring isn’t a single dashboard—it’s a set of well-chosen signals and query-based checks that reflect how your system fails in real life. Start with replica set health and lag, add performance indicators (slow ops and latency), then layer in data-plane alerts that validate business-critical flows. Keep alerts persistent, contextual, and tied to clear actions to avoid noise.
If you prefer running these checks as scheduled queries with mobile notifications, tools like Query Alert can help operationalize the pattern without building a custom alerting pipeline.