Debian系统MongoDB性能调优技巧
storage.wiredTiger.engineConfig.cacheSizeGB参数设置),避免内存不足导致频繁磁盘IO。/etc/default/grub,添加GRUB_CMDLINE_LINUX_DEFAULT="quiet numa=off transparent_hugepage=never",更新GRUB(sudo update-grub)并重启系统。NUMA可能导致内存分配不均,Transparent HugePage会增加内存管理开销。/etc/sysctl.conf,增加以下配置以提升网络和内存性能:fs.file-max = 655360 # 增加文件描述符限制
vm.swappiness = 1 # 减少交换分区使用(设为1-10)
net.core.somaxconn = 65535 # 提高TCP连接队列长度
执行sudo sysctl -p使配置生效。/etc/mongod.conf,重点优化以下参数:
net.bindIp设置为0.0.0.0(允许远程访问,生产环境需限制IP);net.port保持默认27017或根据需求调整。storage.wiredTiger.engineConfig.cacheSizeGB设为物理内存的50%-80%;storage.wiredTiger.collectionConfig.blockCompressor选择snappy(平衡压缩率与CPU开销,若对延迟敏感可选zstd)。storage.journal.enabled保持true(确保数据持久性);storage.journal.commitIntervalMs调整为100-500(降低提交频率以提升写入性能,但会增加数据丢失风险)。replication.replSetName: "rs0";若数据量大,配置分片集群(sh.enableSharding + sh.shardCollection)。user_id、timestamp)创建单字段索引(db.collection.createIndex({field: 1}));对多条件查询(如status=1 AND create_time>xxx)创建复合索引(db.collection.createIndex({field1: 1, field2: -1}))。db.collection.stats()查看索引大小。db.collection.find({field: 1}, {field: 1, _id: 0})),无需访问实际文档,减少IO。db.collection.find().explain("executionStats")查看索引使用情况,重点关注winningPlan和executionTimeMillis,优化未使用索引的查询。db.collection.find({}, {field1: 1, field2: 1, _id: 0}))仅返回必要字段,减少网络传输和内存消耗。insertMany、updateMany替代单条插入/更新,降低网络往返次数(如批量插入1000条数据比单条插入快5-10倍)。$where、$regex等全表扫描操作(如db.collection.find({name: /abc/})应改为db.collection.find({name: {$regex: "abc", $options: "i"}})并创建索引)。$match阶段尽早过滤数据,减少后续阶段的处理量(如db.collection.aggregate([{ $match: {status: 1} }, { $group: {...}}]))。rs.initiate({_id: "rs0", members: [{_id: 0, host: "mongo1:27017"}, {_id: 1, host: "mongo2:27017"}, {_id: 2, host: "mongo3:27017"}]})),提升读取性能(将读请求分发到从节点)和数据冗余(自动故障转移)。user_id、timestamp)分片(sh.shardCollection("db.collection", {shardKey: 1})),将数据分布到多个节点,提升读写吞吐量和水平扩展能力。mongostat(实时查看QPS、延迟、IO等指标)、mongotop(查看集合级读写热点)监控性能;开启慢查询日志(operationProfiling.slowOpThresholdMs: 100,记录执行时间超过100ms的查询)分析瓶颈。compact命令整理集合碎片(db.runCommand({compact: 'collectionName'}));用repairDatabase回收未使用空间(需停机,db.repairDatabase());定期升级MongoDB版本(获取性能改进和安全修复)。