CentOS上MongoDB性能调优指南
free -h
命令监控内存使用,避免内存溢出导致频繁使用Swap(可通过swapon -s
检查Swap使用情况)。/etc/security/limits.conf
,添加mongod hard nofile 64000
和mongod soft nofile 64000
;编辑/etc/systemd/system.conf
,设置DefaultLimitNOFILE=64000
,然后执行systemctl daemon-reload
使配置生效。echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
和echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
,并在/etc/rc.local
中添加这两条命令(确保开机自启)。noop
或deadline
调度算法(比默认的cfq
更适合随机读写)。执行echo noop | sudo tee /sys/block/sda/queue/scheduler
(sda
为磁盘设备名)。/etc/mongod.conf
中配置storage.wiredTiger.engineConfig.cacheSizeGB
,建议设置为服务器总内存的50%-70%(如8GB内存可设为5GB)。例如:storage:
wiredTiger:
engineConfig:
cacheSizeGB: 5
修改后需重启MongoDB服务:systemctl restart mongod
。systemLog.verbosity
设置为1
(warning级别),减少日志写入量;若需调试,可设置为0
(debug级别),但调试完成后应及时调回。net.maxIncomingConnections
(默认10000)以支持更多并发连接,设置net.socketOptions.tcpNoDelay
为true
(禁用Nagle算法,减少网络延迟)。find
、update
、delete
查询的字段创建索引(如user_id
、status
)。例如:db.users.createIndex({user_id: 1})
(1
表示升序,-1
表示降序)。{status: "active", age: {$gt: 18}}
并按create_time
降序排序,复合索引应为{status: 1, age: 1, create_time: -1}
。{name: 1, age: 1}
可覆盖查询{name: "John", age: 25}
(需排除_id
字段,或将其加入索引)。db.collection.aggregate([{ $indexStats: {} }])
查看索引使用情况,删除accesses.ops
为0的索引(如db.users.dropIndex("unused_index_name")
)。{a: 1, b: 1}
,无需再创建{a: 1}
(前者已包含后者)。explain()
方法分析查询执行计划,关注winningPlan
中的indexName
(是否命中索引)、executionStats
中的docsExamined
(扫描文档数)、keysExamined
(扫描索引键数)。例如:db.users.find({user_id: 123}).explain("executionStats")
。db.users.find({status: "active"}, {name: 1, email: 1, _id: 0})
(_id: 0
表示不返回_id
字段)。find({status: "active"})
需为status
字段创建索引)。insertMany
)、更新(bulkWrite
)可减少网络往返次数,提高吞吐量。例如:db.users.insertMany([{name: "John"}, {name: "Jane"}])
。skip
(跳过大量文档),改用基于范围的查询(如find({age: {$gt: 20}}).sort({age: 1}).limit(10)
),或记录上次查询的_id
,下次查询{age: {$gt: 20}, _id: {$gt: last_id}}
。/etc/mongod.conf
中设置replication.replSetName: "rs0"
,然后初始化副本集:rs.initiate()
,添加从节点:rs.add("secondary_host:27017")
。user_id
),配置sharding.clusterRole: "shardsvr"
,并添加分片到集群:sh.addShard("shard1_host:27017")
。mongostat
(查看每秒操作数、读写延迟)、mongotop
(查看集合级读写时间)监控性能。例如:mongostat --host localhost:27017
。operationProfiling.slowOpThresholdMs: 100
,单位毫秒),分析执行慢的查询。例如:db.setProfilingLevel(1, 100)
(记录慢于100ms的查询),通过db.system.profile.find().sort({ts: -1}).limit(10)
查看最近的慢查询。