优化MongoDB在CentOS上的性能需从硬件基础、配置调优、索引设计、查询规范、分片与副本集、监控维护六大维度系统推进,以下是具体措施:
硬件是性能的底层支撑,需优先满足以下要求:
storage.wiredTiger.engineConfig.cacheSizeGB配置),避免内存不足导致频繁磁盘交换。通过修改/etc/mongod.conf文件调整核心参数,优化资源利用率:
storage:
engine: wiredTiger
cacheSizeGB(如8GB内存分配6GB给MongoDB),并优化脏页驱逐策略(减少检查点磁盘IO):storage:
wiredTiger:
engineConfig:
cacheSizeGB: 6
evictionTrigger: 90 # 缓存使用达90%时触发驱逐
evictionTarget: 80 # 目标驱逐至80%
eviction_dirty_trigger: 5 # 脏页占比5%时触发写入
eviction_dirty_target: 3 # 目标脏页占比3%
net:
maxIncomingConnections: 5000
socketOptions:
keepAlive: 1 # 开启TCP keepalive
tcpNoDelay: true # 禁用Nagle算法(减少延迟)
SO_REUSEADDR: true # 允许地址复用
operationProfiling:
mode: slowOp # 记录慢查询
slowOpThresholdMs: 100 # 慢查询阈值(毫秒)
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
logRotate: reopen # 日志轮转策略
replication:
journal:
commitIntervalMs: 50 # 更频繁的提交(数据更安全,但IO更高)
索引是提升查询性能的关键,需遵循以下原则:
where、sort、join条件中的字段创建索引(如user_id、created_at):db.collection.createIndex({ field1: 1 }); // 升序索引
db.collection.createIndex({ field1: -1 }); // 降序索引
find({field1: value, field2: value})),创建复合索引(顺序需匹配查询条件):db.collection.createIndex({ field1: 1, field2: -1 }); // 覆盖查询场景
$or(除非字段均有索引)、$in(大量数据时)、$where(JavaScript执行慢)等操作;确保查询条件与索引前缀匹配。reIndex()重建碎片化索引(如数据频繁增删后):db.collection.reIndex();
explain("executionStats")验证索引使用情况:db.collection.find({ field1: value }, { field1: 1, _id: 0 }).explain("executionStats");
优化查询逻辑,减少资源消耗:
explain()检查winningPlan中的IXSCAN步骤)。_id默认返回,可排除):db.collection.find({ field1: value }, { field1: 1, field2: 1, _id: 0 });
skip()在大偏移量时的性能下降(如第1000页),改用基于范围的分页(记录上一页最后一条数据的_id):// 第一页
db.collection.find({ field1: value }).sort({ _id: 1 }).limit(10);
// 第二页(假设上一页最后一条_id为123)
db.collection.find({ field1: value, _id: { $gt: 123 } }).sort({ _id: 1 }).limit(10);
insertMany()、updateMany()替代循环单条操作,减少网络往返次数。针对大规模数据和高可用需求,采用分布式架构:
replication:
replSetName: "rs0" # 副本集名称
user_id,确保数据分布均匀)。持续监控系统状态,及时发现并解决问题:
mongostat(查看QPS、延迟)、mongotop(查看集合级读写时间)监控实时性能;通过db.currentOp()查看当前操作(如长时间运行的查询)。operationProfiling.mode: slowOp),定期分析并优化慢查询。mongodump/mongorestore);更新MongoDB到最新稳定版本(修复性能bug和安全漏洞)。以上方法需根据实际业务场景(如数据量、并发量、查询模式)灵活调整,建议在测试环境验证后再应用于生产环境。