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)查看最近的慢查询。