CentOS环境下MongoDB性能优化指南
storage.wiredTiger.engineConfig.cacheSizeGB配置)。例如,8GB内存服务器可设置cacheSizeGB: 6,确保热点数据常驻内存,减少磁盘I/O。echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
并在/etc/rc.local中添加上述命令,确保重启后生效。/etc/security/limits.conf,添加:mongod soft nofiles 64000
mongod hard nofiles 64000
mongod soft nproc 64000
mongod hard nproc 64000
同时修改/etc/systemd/system/mongod.service.d/override.conf(若使用systemd),添加:[Service]
LimitNOFILE=64000
LimitNPROC=64000
重启systemd和mongod使配置生效。/etc/sysctl.conf:net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
fs.file-max = 100000
执行sysctl -p使配置生效。storage.engine: wiredTiger。storage.wiredTiger.engineConfig.cacheSizeGB(如6GB),避免占用过多内存导致系统交换(swap)。net.maxIncomingConnections(如5000)以支持更多并发连接;开启tcpNoDelay(net.socketOptions.tcpNoDelay: true)减少网络延迟;设置keepAlive(net.socketOptions.keepAlive: 1)避免连接超时。operationProfiling.mode: slowOp,并设置slowOpThresholdMs: 100(阈值可根据业务调整)。日志路径通过systemLog.path指定,启用logAppend: true避免日志覆盖。user_id、created_at)创建索引,使用db.collection.createIndex({field: 1})(1表示升序,-1表示降序)。例如,为文章标题创建索引:db.articles.createIndex({title: 1})。{user_id: 1, created_at: -1}),复合索引能减少索引数量,提高查询效率。注意字段顺序,将选择性高的字段放在前面。title和author字段,可创建索引db.articles.createIndex({title: 1, author: 1}),并使用投影{title: 1, author: 1, _id: 0}。db.collection.reIndex()重建碎片化索引,提升查询性能;通过db.collection.stats()监控索引大小和使用情况,删除未使用的索引。explain("executionStats")分析执行计划);减少不必要的字段返回,使用投影(如{title: 1, _id: 0})降低数据传输量。skip()和limit()分页(如db.articles.find().skip(10).limit(5)),避免一次性返回过多数据导致内存溢出。$or查询可能导致索引失效,尽量改用$in或拆分查询。例如,将{status: {$or: ["active", "pending"]}}改为{status: {$in: ["active", "pending"]}}。insertMany()、updateMany()代替循环的单条操作,减少网络往返次数,提高写入效率。replication.replSetName)提升读取性能和高可用性。将读操作分流到从节点(readPreference: secondary),减轻主节点压力。sharding.clusterRole)将数据水平切分到多个分片。选择合适的分片键(如user_id),避免热点问题(如单调递增的分片键会导致写入集中)。mongostat监控每秒操作数、读写延迟;mongotop查看集合级别的读写时间分布;explain()分析查询执行计划。operationProfiling.slowOpThresholdMs设置阈值),优化高频慢查询,避免性能瓶颈。