10. MongoDB 性能调优与运维监控

MongoDB Profiler、Explain 分析、WiredTiger 缓存、慢查询优化与生产监控指标

MongoDB 的性能取决于存储引擎、索引使用、查询模式和工作负载特征。系统的调优策略包括 Profiler 分析、explain 诊断、内存参数调整和操作系统层面的优化。

1. WiredTiger 存储引擎

1.1 缓存配置

# mongod.conf
storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4  # 默认 = (RAM - 1GB) / 2
// 运行时查看缓存状态
db.serverStatus().wiredTiger.cache
// {
//   "bytes currently in the cache": 2147483648,
//   "maximum bytes configured": 4294967296,
//   "tracked dirty bytes in the cache": 10485760
// }

内存使用分配

总 RAM 32GB
  ├── WiredTiger Cache:     ~15GB  ((32-1)/2)
  ├── 索引和其他:            ~5GB
  ├── 连接/线程栈:           ~2GB
  └── OS 文件系统缓存(剩余)  ~10GB  ← 可加速冷数据读取

1.2 页驱逐策略

// 脏页比例高时触发写入,避免突发的 write burst
db.serverStatus().wiredTiger.cache['dirty percentage in the cache']
// 应保持在 20% 以下

2. 慢查询分析

2.1 启用 Profiler

// 开启慢查询收集(>100ms)
db.setProfilingLevel(1, { slowms: 100 });
// 0 = 关闭, 1 = 慢查询, 2 = 所有查询

// 查看慢查询
db.system.profile.find().sort({ ts: -1 }).limit(10);

// 常用分析查询
db.system.profile.aggregate([
    { $match: { op: "query" } },
    { $group: {
        _id: "$ns",
        avgTime: { $avg: "$millis" },
        maxTime: { $max: "$millis" },
        count: { $sum: 1 }
    }},
    { $sort: { avgTime: -1 } }
]);

2.2 查询优化检查清单

问题诊断解决
COLLSCANexplain 显示无索引创建合适的索引
内存排序executionStats.totalDocsExamined >> nReturned复合索引包含排序字段
大量 docsExamined查询未有效利用索引$match 添加更多过滤条件
写入延迟writeConcern: majority降低 w (权衡一致性)
锁争用db.serverStatus().locks分片/优化查询

3. 连接与并发

# mongod.conf
net:
  maxIncomingConnections: 1000      # 默认 65536,根据 ulimit 调整

# ulimit 配置 (Linux)
# -n  文件描述符: 64000
# -u  最大进程数: 64000
# -m  虚拟内存: unlimited

4. 监控关键指标

指标收集方式健康阈值
opcountersdb.serverStatus().opcounters稳定趋势
连接数db.serverStatus().connections< 80% maxConnections
内存使用db.serverStatus().memresident < RAM * 80%
oplog 窗口rs.printReplicationInfo()> 24 小时
复制延迟rs.printSlaveReplicationInfo()< 10 秒
锁等待db.currentOp()无长时间等待

延伸阅读

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「mongodb」更多文章

  1. 11. MongoDB 安全认证与备份恢复
  2. 09. Spring Data MongoDB 实战
  3. 08. MongoDB Change Streams 实时同步