CentOS下MongoDB性能调优指南
cacheSizeGB: 6),避免内存不足导致频繁磁盘交换(Swap)。systemctl stop firewalld)或禁用SELinux(setenforce 0),减少系统负载(仅适用于测试环境;生产环境需权衡安全性)。/etc/security/limits.conf,添加以下内容(针对mongod用户):mongod soft nofiles 64000mongod hard nofiles 64000mongod soft nproc 64000mongod hard nproc 64000ulimit -n 64000和ulimit -u 64000使设置生效。/etc/fstab,为数据目录添加noatime选项(如/dev/xvdb /data ext4 noatime 0 0),然后执行mount -o remount /data,减少文件访问时间更新带来的磁盘I/O。echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabledecho never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag/etc/rc.local中,确保开机自动生效。/etc/mongod.conf中设置storage.wiredTiger.engineConfig.cacheSizeGB(如4),根据服务器内存调整(建议不超过总内存的75%)。systemLog.verbosity设置为1(warning),减少日志输出量,降低磁盘I/O;调试时可设置为0(debug)。net.maxIncomingConnections(如5000),允许更多并发连接;开启tcpNoDelay(net.socketOptions.tcpNoDelay: true)和keepAlive(net.socketOptions.keepAlive: 1),减少网络延迟。replication.replSetName设置副本集名称(如rs0),提高数据冗余和读取性能(从节点可处理读请求);sh.enableSharding()和sh.shardCollection()将数据水平切分到多个分片,提高写入和查询性能。find、sort、group的字段创建索引(如db.articles.createIndex({title: 1}));复合索引需根据查询模式设计(如db.articles.createIndex({author_id: 1, created_at: -1}),适合按作者ID查询并按时间倒序排序的场景)。db.articles.find({title: "MongoDB"}, {_id: 0, title: 1}),若title有索引,则无需读取文档)。explain("executionStats")分析查询执行计划,确保查询使用了索引(winningPlan.stage应为IXSCAN而非COLLSCAN);避免使用$or(除非所有子句都有索引),尽量用$in替代。db.collection.reIndex()(如每月一次),尤其是在大量插入、删除操作后。db.users.find({}, {name: 1, email: 1, _id: 0}),避免返回_id字段)。skip和limit分页(如db.orders.find().skip(20).limit(10),跳过前20条,返回10条),避免一次性返回大量数据。insertMany、updateMany替代单条插入/更新(如db.products.insertMany([{name: "A"}, {name: "B"}])),减少网络往返次数。mongostat:监控每秒的读写操作、延迟、锁等待等指标(如mongostat --host 127.0.0.1 --port 27017);mongotop:查看集合级别的读写时间分布(如mongotop --host 127.0.0.1 --port 27017),定位慢集合。/etc/mongod.conf中设置operationProfiling.mode: slowOp,operationProfiling.slowOpThresholdMs: 100),通过db.getProfilingLevel()查看当前级别,用db.system.profile.find()分析慢查询。db.collection.deleteMany({createdAt: {$lt: ISODate("2025-01-01")}}),减少存储空间占用。mongodump和mongorestore定期备份(如每周一次),确保数据安全(备份文件存储在独立磁盘或云存储中)。