Ubuntu上MongoDB性能调优策略
一 硬件与存储基础
二 存储引擎与WiredTiger关键参数
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8
一般单机单实例可沿用默认(约占用内存的60%),多实例或与其他进程混部时按配额设置,避免互相抢占。db.runCommand({
setParameter: 1,
wiredTigerEngineRuntimeConfig: "eviction=(threads_max=8,threads_min=4)"
})
三 索引与查询优化
// 等值 + 排序 的复合索引
db.orders.createIndex({ customerId: 1, orderDate: -1 })
// 覆盖查询(注意排除_id或将其加入索引)
db.posts.createIndex({ status: 1, authorId: 1, createdAt: -1 })
db.posts.find(
{ status: "published", authorId: 1 },
{ title: 1, createdAt: 1, _id: 0 }
).explain("executionStats")
对字符串比较需匹配Collation;对**$or**查询应为每个子句单独建立最优索引。四 连接与操作系统调优
* soft nofile 1048576
* hard nofile 1048576
* soft nproc 524288
* hard nproc 524288
并在MongoDB配置中按需调整net.maxIncomingConnections(注意总连接数受系统限制约束)。db.adminCommand({ setParameter: 1, tcmallocReleaseRate: 5.0 })
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
五 监控 诊断 与维护
db.serverStatus().mem
db.serverStatus().wiredTiger.cache
db.serverStatus().tcmalloc