CentOS上MongoDB性能调优技巧
storage.wiredTiger.engineConfig.cacheSizeGB参数调整(如/etc/mongod.conf中设置cacheSizeGB: 8)。避免内存不足导致频繁磁盘I/O。find、sort、update的字段创建索引(如user_id、order_date)。使用db.collection.createIndex()方法(如db.orders.createIndex({user_id: 1, order_date: -1})),避免全表扫描。db.users.createIndex({status: 1, age: 1})可优化status=1 AND age>25的查询,同时支持status=1的单字段查询。{name: 1, gender: 1}可支持db.users.find({gender: "male"}, {name: 1, _id: 0})的覆盖查询,减少磁盘I/O。db.collection.explain("executionStats")分析查询执行计划,删除未使用或低效索引(如db.collection.dropIndex("index_name"));通过db.collection.reIndex()重建碎片化索引,提升索引效率。mongod.conf中设置storage.engine: wiredTiger。storage.wiredTiger.engineConfig.cacheSizeGB参数,根据服务器内存设置(如8GB内存可设为5-6GB),平衡数据库与其他应用的内存使用。net.maxIncomingConnections(如5000)提升并发连接能力;开启tcpNoDelay(net.socketOptions.tcpNoDelay: true)减少网络延迟;设置keepAlive(net.socketOptions.keepAlive: 1)防止连接超时。systemLog.verbosity设置为1(warning级别),减少不必要的日志输出;开启日志轮转(systemLog.logRotate: reopen),避免日志文件过大占用磁盘空间。{field: 1}仅返回需要的字段,减少数据传输量。例如,db.users.find({}, {name: 1, email: 1, _id: 0})只返回name和email字段。limit()限制结果集数量(如db.orders.find().limit(100));对排序字段建立索引,避免SORT阶段内存溢出(如db.orders.createIndex({order_date: -1}))。skip()+limit())避免一次性获取大量数据,但需注意skip()在大偏移量时的性能问题(建议用范围查询替代,如db.orders.find({order_date: {$gt: last_date}}).limit(20))。explain()检查查询是否使用索引(winningPlan.stage为IXSCAN),优化查询条件使其命中索引。user_id),避免数据倾斜(热点问题)。使用sh.enableSharding()启用分片,sh.shardCollection()为集合分片。rs.initiate({_id: "rs0", members: [{_id: 0, host: "server1:27017"}, {_id: 1, host: "server2:27017"}, {_id: 2, host: "server3:27017"}]})),读操作可指向secondary节点(readPreference: "secondaryPreferred"),减轻主节点压力。mongostat监控每秒操作数(如insert、query)、mongotop查看集合级读写时间,实时掌握数据库性能状态。operationProfiling.mode: "slowOp"(默认100ms),记录慢查询日志(operationProfiling.slowOpThresholdMs),通过db.system.profile.find()分析慢查询原因(如未命中索引),针对性优化。