Monitor MongoDB 8.0 performance with Prometheus and Grafana for real-time metrics and alerting

Intermediate 45 min Apr 17, 2026 164 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Set up comprehensive MongoDB performance monitoring using Prometheus metrics collection and Grafana dashboards with alerting rules for database health, connection pools, and query performance.

Prerequisites

  • MongoDB 8.0 installed and running
  • Prometheus server installed
  • Grafana installed
  • Basic MongoDB administration knowledge

What this solves

MongoDB performance monitoring requires real-time visibility into database metrics like query execution times, connection pool status, replica set health, and resource utilization. This tutorial shows you how to collect MongoDB metrics with Prometheus and visualize them in Grafana dashboards with automated alerting for production database environments.

Step-by-step configuration

Install MongoDB Exporter for Prometheus

The MongoDB Exporter collects database metrics and exposes them in Prometheus format. Download and install the latest version.

wget https://github.com/percona/mongodb_exporter/releases/download/v0.40.0/mongodb_exporter-0.40.0.linux-amd64.tar.gz
tar -xzf mongodb_exporter-0.40.0.linux-amd64.tar.gz
sudo mv mongodb_exporter-0.40.0.linux-amd64/mongodb_exporter /usr/local/bin/
sudo chmod +x /usr/local/bin/mongodb_exporter

Create MongoDB monitoring user

Create a dedicated MongoDB user with minimal permissions for metrics collection. This user needs read access to database statistics and replica set status.

mongosh --host localhost:27017
use admin
db.createUser({
  user: "prometheus_monitor",
  pwd: "secure_monitoring_password_2024",
  roles: [
    { role: "read", db: "admin" },
    { role: "read", db: "local" },
    { role: "clusterMonitor", db: "admin" },
    { role: "readAnyDatabase", db: "admin" }
  ]
})
exit

Configure MongoDB Exporter service

Create a systemd service for the MongoDB Exporter with authentication credentials and collection settings.

[Unit]
Description=MongoDB Prometheus Exporter
After=network.target

[Service]
Type=simple
User=nobody
Group=nogroup
Environment=MONGODB_URI=mongodb://prometheus_monitor:secure_monitoring_password_2024@localhost:27017/admin
ExecStart=/usr/local/bin/mongodb_exporter --mongodb.uri=$MONGODB_URI --collect-all --web.listen-address=:9216
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Start and enable MongoDB Exporter

Enable the exporter service to start automatically and verify it's collecting metrics properly.

sudo systemctl daemon-reload
sudo systemctl enable --now mongodb-exporter
sudo systemctl status mongodb-exporter

Configure Prometheus to scrape MongoDB metrics

Add MongoDB Exporter as a scrape target in your Prometheus configuration. This assumes you have Prometheus installed and running.

global:
  scrape_interval: 15s
  evaluation_interval: 15s

rule_files:
  - "mongodb_alerts.yml"

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'mongodb'
    static_configs:
      - targets: ['localhost:9216']
    scrape_interval: 30s
    metrics_path: /metrics

Create MongoDB alerting rules

Define alert conditions for MongoDB performance issues, connection problems, and replica set failures.

groups:
  • name: mongodb.rules
rules: - alert: MongoDBDown expr: mongodb_up == 0 for: 5m labels: severity: critical annotations: summary: "MongoDB instance is down" description: "MongoDB instance {{ $labels.instance }} has been down for more than 5 minutes." - alert: MongoDBHighConnections expr: mongodb_connections{state="current"} / mongodb_connections{state="available"} > 0.8 for: 2m labels: severity: warning annotations: summary: "MongoDB connection usage high" description: "MongoDB instance {{ $labels.instance }} is using {{ $value | humanizePercentage }} of available connections." - alert: MongoDBSlowQueries expr: rate(mongodb_op_latencies_ops_total{type="command"}[5m]) > 100 for: 2m labels: severity: warning annotations: summary: "MongoDB slow queries detected" description: "MongoDB instance {{ $labels.instance }} is experiencing {{ $value }} slow queries per second." - alert: MongoDBReplicaLag expr: mongodb_replset_member_replication_lag > 10 for: 1m labels: severity: critical annotations: summary: "MongoDB replica lag high" description: "MongoDB replica {{ $labels.instance }} is lagging by {{ $value }} seconds." - alert: MongoDBHighMemoryUsage expr: mongodb_memory{type="resident"} / 1024 / 1024 > 4000 for: 5m labels: severity: warning annotations: summary: "MongoDB high memory usage" description: "MongoDB instance {{ $labels.instance }} is using {{ $value }}MB of memory."

Restart Prometheus with new configuration

Reload Prometheus configuration to start collecting MongoDB metrics and enable alerting rules.

sudo systemctl restart prometheus
sudo systemctl status prometheus

Import MongoDB dashboard into Grafana

Create a comprehensive Grafana dashboard for MongoDB monitoring. First, access your Grafana instance and import a dashboard configuration.

curl -s https://raw.githubusercontent.com/percona/grafana-dashboards/main/dashboards/MongoDB_Overview.json > mongodb_dashboard.json

Configure custom MongoDB dashboard

Create a custom dashboard with key MongoDB performance panels. Log into Grafana and create a new dashboard with these essential panels.

{
  "dashboard": {
    "title": "MongoDB Performance",
    "panels": [
      {
        "title": "MongoDB Status",
        "type": "stat",
        "targets": [{
          "expr": "mongodb_up",
          "legendFormat": "MongoDB Up"
        }]
      },
      {
        "title": "Operations per Second",
        "type": "graph",
        "targets": [{
          "expr": "rate(mongodb_op_counters_total[5m])",
          "legendFormat": "{{ type }}"
        }]
      },
      {
        "title": "Connection Usage",
        "type": "graph",
        "targets": [{
          "expr": "mongodb_connections",
          "legendFormat": "{{ state }}"
        }]
      },
      {
        "title": "Memory Usage",
        "type": "graph",
        "targets": [{
          "expr": "mongodb_memory",
          "legendFormat": "{{ type }}"
        }]
      },
      {
        "title": "Query Execution Time",
        "type": "graph",
        "targets": [{
          "expr": "mongodb_op_latencies_latency_total / mongodb_op_latencies_ops_total",
          "legendFormat": "{{ type }}"
        }]
      }
    ]
  }
}

Configure Grafana alerts

Set up Grafana alerts that complement your Prometheus alerting rules. Configure notification channels for email or Slack integration.

curl -X POST http://localhost:3000/api/alert-notifications \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_GRAFANA_API_KEY" \
  -d '{
    "name": "mongodb-alerts",
    "type": "email",
    "settings": {
      "addresses": "admin@example.com",
      "subject": "MongoDB Alert: {{ .Title }}"
    }
  }'

Configure replica set monitoring

If you're running a MongoDB replica set, add specific monitoring for replica lag and election status.

groups:
  • name: mongodb.replica
rules: - alert: MongoDBReplicaSetDown expr: mongodb_replset_number_of_members - mongodb_replset_number_of_members{state="PRIMARY"} - mongodb_replset_number_of_members{state="SECONDARY"} > 0 for: 1m labels: severity: critical annotations: summary: "MongoDB replica set member down" description: "MongoDB replica set has unhealthy members." - alert: MongoDBNoPrimary expr: mongodb_replset_number_of_members{state="PRIMARY"} == 0 for: 30s labels: severity: critical annotations: summary: "MongoDB replica set has no primary" description: "MongoDB replica set {{ $labels.set }} has no primary member."

Configure advanced monitoring features

Enable MongoDB profiler for slow query tracking

Configure MongoDB's built-in profiler to capture slow queries for analysis in your monitoring dashboard.

mongosh --host localhost:27017
use admin
db.runCommand({ profile: 2, slowms: 100 })
db.system.profile.createIndex({ "command.find": 1 })
db.system.profile.createIndex({ "command.aggregate": 1 })
exit

Configure index usage monitoring

Set up monitoring for index usage statistics to identify missing or unused indexes affecting performance.

groups:
  • name: mongodb.indexes
rules: - alert: MongoDBCollectionScans expr: rate(mongodb_metrics_query_executor_total{state="collectionScans"}[5m]) > 10 for: 2m labels: severity: warning annotations: summary: "High collection scans detected" description: "MongoDB is performing {{ $value }} collection scans per second, consider adding indexes." - alert: MongoDBHighIndexMisses expr: rate(mongodb_metrics_cursor_total{state="totalNoTimeout"}[5m]) / rate(mongodb_metrics_cursor_total{state="totalOpened"}[5m]) < 0.9 for: 5m labels: severity: warning annotations: summary: "Low index hit ratio" description: "MongoDB index hit ratio is {{ $value | humanizePercentage }}, review query patterns."

Verify your setup

Check that all monitoring components are working correctly and collecting metrics.

curl http://localhost:9216/metrics | grep mongodb_up
curl http://localhost:9090/api/v1/query?query=mongodb_up
sudo systemctl status mongodb-exporter prometheus grafana-server

Access your Grafana dashboard at http://your-server:3000 and verify that MongoDB metrics are being displayed correctly. Check that alerts are configured in both Prometheus and Grafana.

Note: It may take 1-2 minutes for metrics to appear in Grafana after starting the exporter. Check the Prometheus targets page at http://localhost:9090/targets to ensure the MongoDB exporter is being scraped successfully.

Common issues

SymptomCauseFix
Exporter shows "connection refused"MongoDB authentication failureVerify MongoDB user credentials and permissions with mongosh
Missing replica set metricsExporter not connected to replica setUpdate MONGODB_URI to include replica set name: mongodb://user:pass@host/admin?replicaSet=rs0
High memory usage alerts firingIncorrect memory thresholdsAdjust alert thresholds in mongodb_alerts.yml based on your server capacity
Prometheus not scraping metricsNetwork connectivity or firewallTest connectivity: curl http://localhost:9216/metrics and check firewall rules
Grafana shows no dataPrometheus data source misconfiguredVerify Prometheus data source URL in Grafana settings: http://localhost:9090
Alerts not firingAlert rules syntax errorsValidate alert rules: promtool check rules /etc/prometheus/mongodb_alerts.yml

Next steps

Running this in production?

Want this handled for you? Setting this up once is straightforward. Keeping it patched, monitored, backed up and performant across environments is the harder part. See how we run infrastructure like this for European teams.

Automated install script

Run this to automate the entire setup

Need help?

Don't want to manage this yourself?

We handle managed devops services for businesses that depend on uptime. From initial setup to ongoing operations.