MongoDB Alerting: Query-Driven Rules to Detect Issues Fast

Published Apr 16, 2026

Learn MongoDB alerting patterns with practical queries, thresholds, deduping, and secure setups to catch incidents early without alert fatigue.

MongoDB Alerting: Query-Driven Rules to Detect Issues Fast

MongoDB alerting works best when alerts are grounded in data you can explain, reproduce, and act on. Instead of relying only on generic host metrics, query-driven alerts let you detect business-impacting changes (failed payments, backlog growth, missing documents) and operational risks (replication lag symptoms, error spikes, runaway writes) directly from the database.

This guide walks through practical MongoDB alerting patterns, with example queries, rule design techniques to reduce noise, and security considerations for running checks safely.

What “good” MongoDB alerting looks like

Effective alerts share three traits:

  • Actionable: the on-call person knows what to do next.
  • Bounded: the alert fires for a specific condition, with a clear threshold or anomaly definition.
  • Low-noise: duplicates are suppressed, flapping is controlled, and expected spikes are handled.

To reach that standard, you typically combine three sources:

  • Database metrics (CPU, memory, connections, replication, disk, ops/sec)
  • Log-derived events (timeouts, authentication failures, slow queries)
  • Query results that represent application health and business correctness

Approaches to MongoDB alerting (and when to use each)

Approach Best for Pros Cons
Query polling (scheduled checks) KPIs, backlogs, correctness checks Simple, works everywhere, easy to explain Interval-based, may miss short spikes
Change Streams Near-real-time document changes Low latency, event-driven Operational complexity, needs replica set/sharded config
Platform metrics/telemetry Infra-level reliability Great for saturation/outages Often less tied to business impact

In practice, teams often start with polling (fastest to adopt), then add Change Streams for high-value real-time events, and keep metrics for baseline infrastructure monitoring.

Designing query-driven alerts that don’t spam you

1) Pick a “signal” collection (or build one)

Alerts are easiest when the data model supports them. Many systems already have an events, jobs, outbox, audit, or transactions collection that can be queried for health signals. If you don’t, consider adding a lightweight “status/event” write from your app to make monitoring measurable.

2) Use rolling windows

Instead of “count all failures today,” prefer “count failures in the last 5 minutes.” That reduces false positives and makes the alert state reflect what’s happening now.

3) Add deduplication and hysteresis

  • Dedup: don’t alert on the same condition every minute. Send once, then wait until it clears or worsens.
  • Hysteresis: use different thresholds to trigger vs. clear. Example: trigger at 100 queued jobs, clear at 60.

4) Include context in the result

Return a small payload of “what changed” with the alert: top error messages, worst tenants, largest backlogs, or sample IDs. The best alert is also a mini triage report.

Practical MongoDB alerting patterns (with queries)

The examples below use ISODate() and assume you have indexes on key filter fields like timestamps and status.

Pattern A: Spike in errors (rolling window)

Use an aggregation pipeline to count errors in the last 5 minutes and break them down by type.

db.app_events.aggregate([
  {
    $match: {
      level: "error",
      createdAt: { $gte: new Date(Date.now() - 5 * 60 * 1000) }
    }
  },
  {
    $group: {
      _id: "$errorCode",
      count: { $sum: 1 },
      latest: { $max: "$createdAt" }
    }
  },
  { $sort: { count: -1 } },
  { $limit: 5 }
])

Alert rule idea: trigger if total errors > 50 in 5 minutes or if any single errorCode exceeds 20. Include the top 5 codes in the notification.

Pattern B: Backlog growth (queued jobs / outbox)

Backlog alerts are often more actionable than CPU alerts because they indicate user-visible delays.

db.jobs.aggregate([
  { $match: { status: "queued" } },
  {
    $group: {
      _id: "$queue",
      queued: { $sum: 1 },
      oldestQueuedAt: { $min: "$createdAt" }
    }
  },
  { $sort: { queued: -1 } }
])

Alert rule idea: trigger if any queue has queued > 1000 or if oldestQueuedAt is older than 10 minutes. This catches both volume and “stuck worker” scenarios.

Pattern C: Missing data (freshness / heartbeat)

Freshness checks catch silent failures: a pipeline stopped, a partner feed halted, or a cron job broke.

db.ingestions.find(
  { source: "partnerA" },
  { receivedAt: 1 }
).sort({ receivedAt: -1 }).limit(1)

Alert rule idea: trigger if newest receivedAt is older than 15 minutes (adjust per SLA). For multi-tenant systems, run the same query grouped by tenant and alert on the worst offenders.

Pattern D: Guardrails for “runaway writes”

Sometimes you want to detect anomalous growth in a high-churn collection (sessions, events, logs) before it becomes a cost or performance incident.

db.app_events.aggregate([
  {
    $match: {
      createdAt: { $gte: new Date(Date.now() - 60 * 60 * 1000) }
    }
  },
  {
    $group: {
      _id: { $dateTrunc: { date: "$createdAt", unit: "minute" } },
      perMinute: { $sum: 1 }
    }
  },
  { $sort: { "_id": 1 } }
])

Alert rule idea: compute a baseline (e.g., median per-minute rate over the last day) and trigger if the current rate exceeds baseline by 3–5× for 3 consecutive checks.

Change Streams for near-real-time MongoDB alerting

If you need immediate notification for specific document changes (e.g., “payment status changed to failed”), Change Streams can push events as they happen. A common pattern is filtering the stream heavily and then alerting only on high-severity transitions.

// Node.js example (conceptual)
const pipeline = [
  {
    $match: {
      "fullDocument.status": "failed",
      "fullDocument.type": "payment"
    }
  }
];

const changeStream = db.collection("transactions").watch(pipeline, {
  fullDocument: "updateLookup"
});

changeStream.on("change", (change) => {
  // Send alert with change.fullDocument.id, userId, amount, etc.
});

Operational note: Change Streams require a replica set (or sharded cluster) and careful handling of resume tokens, restarts, and backpressure. For many teams, polling is still the fastest, most reliable first step—then add Change Streams selectively where latency matters.

Security and access: alert safely with least privilege

MongoDB alerting checks should be designed to minimize risk:

  • Use read-only credentials scoped to the collections you query.
  • Prefer narrow projections (only return the fields needed for alert context).
  • Encrypt in transit (TLS) and restrict network access (IP allowlists / VPN / private networking).
  • Avoid sensitive data in alerts—use IDs and summaries rather than full documents.

A helpful rule: if you wouldn’t paste the alert payload into a shared chat, don’t include it in an email/push notification.

Performance tips: keep alert queries cheap

Alerting is “background traffic.” It should never become the reason your database is slow.

  • Index the filters you alert on (e.g., { createdAt: 1, level: 1 } for error windows, { status: 1, createdAt: 1 } for queued jobs).
  • Use time-bounded matches so the working set stays small.
  • Limit results and aggregate only what you need (top N, totals, newest/oldest).
  • Separate analytics from OLTP when possible: if an alert needs heavy scans, consider pre-aggregations or a reporting store.

Example alert definitions you can copy

  1. Error spike: “Errors in last 5m > 50 OR any errorCode > 20; include top 5 codes.”
  2. Backlog: “Queued jobs > 1000 OR oldest queued job age > 10m; include queue name and oldest timestamp.”
  3. Freshness: “No ingestion from partnerA in 15m; include last receivedAt and last file/batch ID.”
  4. Runaway writes: “Event rate > 5× baseline for 3 checks; include per-minute rate trend.”

Putting it together: an alerting workflow that scales

A pragmatic MongoDB alerting workflow looks like this:

  • Define signals (what conditions represent impact?)
  • Write the query (time-bounded, indexed, returns context)
  • Choose evaluation (polling interval or Change Streams)
  • Add noise controls (dedup, hysteresis, consecutive failures)
  • Route notifications (email/push/on-call) with severity levels
  • Review monthly (remove noisy alerts, tune thresholds, add missing signals)

Final note

Query-driven MongoDB alerting is powerful because it ties alerts to the exact data your system depends on. If you want an iOS-friendly way to run read-only database queries on a schedule and turn results into notifications, you can explore Query Alert as one option.