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 查询优化检查清单
| 问题 | 诊断 | 解决 |
|---|---|---|
| COLLSCAN | explain 显示无索引 | 创建合适的索引 |
| 内存排序 | 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. 监控关键指标
| 指标 | 收集方式 | 健康阈值 |
|---|---|---|
| opcounters | db.serverStatus().opcounters | 稳定趋势 |
| 连接数 | db.serverStatus().connections | < 80% maxConnections |
| 内存使用 | db.serverStatus().mem | resident < RAM * 80% |
| oplog 窗口 | rs.printReplicationInfo() | > 24 小时 |
| 复制延迟 | rs.printSlaveReplicationInfo() | < 10 秒 |
| 锁等待 | db.currentOp() | 无长时间等待 |
延伸阅读
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。