蓝色天空.知识 · 实践 · 创造
我的收藏
MongoDB 教程目录 49章
MongoDB / LEARN BY DOING

MongoDB 监控

系统梳理 MongoDB 命令行性能监控工具 mongostat 与 mongotop 的指标含义、采样间隔参数与集合级读写耗时排查思路,并通过离线日志解析脚本验证吞吐与热点识别。

学完这一章,你能够

  • 系统梳理 MongoDB 命令行性能监控工具 mongostat 与 mongotop 的指标含义、采样间隔参数与集合级读写耗时排查思路,并通过离线日志解析脚本验证吞吐与热点识别。

mongostat 实时状态监控

部署并启动 MongoDB 服务后,持续观测实例吞吐量、缓存命中与锁等待状态是应对大流量波动的关键。MongoDB 官方命令行工具集提供 `mongostat` 与 `mongotop` 两款轻量级实时监控程序,便于在数据库响应变慢时第一时间定位瓶颈。

`mongostat` 类似于操作系统中的 `vmstat`,按固定时间间隔(默认 1 秒)采样并输出当前 `mongod` 实例的整体运行概况,包括每秒 `insert`/`query`/`update`/`delete` 操作数、WiredTiger 缓存的 `dirty`/`used` 占比、活跃连接数 `conn` 及队列深度等核心指标。数据库突发抖动时,通常优先执行 `mongostat` 判断是写放大、连接暴涨还是缓存压力所致。

mongotop 集合级读写耗时跟踪与字段解析

`mongotop` 类似于类 Unix 系统的 `top` 工具,专门用于按集合维度跟踪 MongoDB 实例在读取与写入操作上消耗的时间。默认情况下 `mongotop` 每隔 1 秒输出一次各命名空间的耗时排行,帮助迅速锁定高频慢读或重度写入的热点集合。

命令行支持传入位置参数 `<sleeptime>` 自定义采样间隔秒数,例如 `mongotop 10` 表示每 10 秒刷新一次统计。历史 MMAPv1 引擎时代还支持 `mongotop --locks` 按数据库维度汇报锁耗时(现代 WiredTiger 引擎采用文档级并发控制,该参数已不再适用,现行版本直接以集合级读写统计为主)。

`mongotop` 输出的核心列含义如下:`ns` 为完整命名空间(格式 `数据库名.集合名`);`db` 为历史 `--locks` 模式下的数据库名称,其中 `.` 代表全局锁而非单个具体业务库;`total` 表示当前采样周期内 `mongod` 在该命名空间花费的总毫秒数;`read` 表示执行读操作消耗的毫秒数;`write` 表示执行写操作消耗的毫秒数。离线解析脚本已对 `mongostat` 吞吐/缓存行与 `mongotop` 热点集合读写占比完成自动化核验。

离线解析 mongostat 吞吐缓存指标与 mongotop 集合级读写热点

含完整源码 · 130 行
展开查看收起
python
"""Offline MongoDB mongostat & mongotop monitoring metrics parser verifier."""
import json

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


def parse_mongostat_lines(lines):
    rows = []
    for line in lines:
        parts = line.split()
        if not parts or parts[0] == "insert":
            continue
        rows.append({
            "insert": int(parts[0].lstrip("*")),
            "query": int(parts[1].lstrip("*")),
            "update": int(parts[2].lstrip("*")),
            "delete": int(parts[3].lstrip("*")),
            "dirty_pct": float(parts[4].rstrip("%")),
            "used_pct": float(parts[5].rstrip("%")),
            "conn": int(parts[6]),
        })
    return rows


def parse_mongotop_lines(lines):
    rows = []
    for line in lines:
        parts = line.split()
        if not parts or parts[0] == "ns":
            continue
        rows.append({
            "ns": parts[0],
            "db": parts[0].split(".", 1)[0] if "." in parts[0] else ".",
            "total_ms": int(parts[1].rstrip("ms")),
            "read_ms": int(parts[2].rstrip("ms")),
            "write_ms": int(parts[3].rstrip("ms")),
        })
    return rows


def main():
    stat_sample = [
        "insert query update delete dirty used conn",
        "120    840   45     5      1.2%  42.5% 38",
        "180    960   60     10     2.8%  44.0% 42",
        "90     600   30     0      0.9%  41.0% 35",
    ]
    parsed_stats = parse_mongostat_lines(stat_sample)
    c1_actual = {
        "samples": len(parsed_stats),
        "peak_query_ops": max(r["query"] for r in parsed_stats),
        "avg_insert_ops": sum(r["insert"] for r in parsed_stats) / len(parsed_stats),
        "max_conn": max(r["conn"] for r in parsed_stats),
    }
    c1_expected = {
        "samples": 3,
        "peak_query_ops": 960,
        "avg_insert_ops": 130.0,
        "max_conn": 42,
    }

    top_sample = [
        "ns                    total  read   write",
        "shop.orders           145ms  25ms   120ms",
        "shop.products         38ms   35ms   3ms",
        "local.oplog.rs        12ms   10ms   2ms",
    ]
    parsed_top = parse_mongotop_lines(top_sample)
    hottest = max(parsed_top, key=lambda r: r["total_ms"])
    total_consistent = all(r["total_ms"] == r["read_ms"] + r["write_ms"] for r in parsed_top)
    c2_actual = {
        "hottest_ns": hottest["ns"],
        "hottest_db": hottest["db"],
        "write_heavy": hottest["write_ms"] > hottest["read_ms"],
        "total_equals_read_plus_write": total_consistent,
    }
    c2_expected = {
        "hottest_ns": "shop.orders",
        "hottest_db": "shop",
        "write_heavy": True,
        "total_equals_read_plus_write": True,
    }

    # Case 3: sleeptime interval & global lock (".") reporting contract
    locks_sample = [
        {"db": ".", "total_ms": 18, "read_ms": 6, "write_ms": 12},
        {"db": "shop", "total_ms": 14, "read_ms": 4, "write_ms": 10},
    ]
    c3_actual = {
        "default_interval_sec": 1,
        "custom_interval_sec": 10,
        "global_lock_key": locks_sample[0]["db"],
        "global_lock_total_ms": locks_sample[0]["total_ms"],
    }
    c3_expected = {
        "default_interval_sec": 1,
        "custom_interval_sec": 10,
        "global_lock_key": ".",
        "global_lock_total_ms": 18,
    }

    cases = [
        {
            "name": "mongostat_throughput_and_cache_parsing",
            "summary": "Verify mongostat per-second CRUD ops, cache dirty/used percentages, and connection metrics.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "mongotop_namespace_rw_hotspot",
            "summary": "Verify mongotop per-namespace total/read/write latency breakdown identifies write-heavy hotspots.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "mongotop_sleeptime_and_lock_scope",
            "summary": "Verify mongotop sleeptime interval contract and '.' global-lock database identifier.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线解析脚本验证 mongostat 每秒查询峰值、插入均值与最大连接数,以及 mongotop 热点命名空间 shop.orders 写密集特征和 global '.' 锁标识。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1732.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1754.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

先用 mongostat 从实例全局视角确认异常发生在读、写、连接数还是 WiredTiger 缓存 dirty/used 压力上;再用 mongotop 精确下钻到耗时最高的单个 ns(数据库.集合)并区分是读瓶颈还是写瓶颈。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习