Linux环境下MongoDB性能瓶颈破解方法
blockdev --setra 32 /dev/sdb(/dev/sdb为MongoDB存储设备)临时设置,写入/etc/rc.local永久生效。/etc/sysctl.conf,增加并发连接和缓冲区大小(如net.core.somaxconn=32768、net.ipv4.tcp_rmem='1024 4096 16777216'),提升网络吞吐能力。修改后执行sysctl -p生效。systemctl stop firewalld)、禁用SELinux(setenforce 0),减少系统负载。vm.swappiness=0(临时)或写入/etc/sysctl.conf(永久),避免系统过度使用Swap,防止MongoDB因内存不足导致性能下降。/etc/mongod.conf中设置storage.wiredTiger.engineConfig.cacheSizeGB,建议值为服务器内存的50%-75%(如16GB内存可设为8GB-12GB),避免缓存过大占用过多内存或过小导致频繁磁盘访问。/etc/security/limits.conf,增加MongoDB用户的文件描述符限制(如mongod hard nofile 65535、mongod soft nofile 65535),避免高并发时因文件描述符不足导致连接失败。find、sort的字段创建索引(如db.collection.createIndex({username: 1}))。db.collection.createIndex({field1: 1, field2: -1}))。db.collection.find({field1: value}, {field1: 1, field2: 1}))。db.collection.getIndexes()查看现有索引,删除不再使用的索引(如db.collection.dropIndex({old_field: 1})),减少内存占用和写入开销。db.collection.reIndex()重建碎片化索引,优化索引性能,尤其适合数据频繁更新的集合。db.collection.find({age: {$gt: 18}}, {name: 1, age: 1, _id: 0}))。skip()+limit()(大数据量时性能差),改用_id分页(如db.collection.find({_id: {$gt: lastObjectId}}).limit(10))。$regex+^(如db.collection.find({name: /^John/})),比全模糊匹配效率高。db.setProfilingLevel(2)),使用explain("executionStats")查看查询计划,找出未使用索引或执行慢的查询并优化。$ref引用关联集合,避免文档过大。user_id、order_id),避免数据倾斜(如避免使用单调递增的字段作为分片键)。readPreference=secondary),减轻主节点压力。mongostat(查看QPS、延迟)、mongotop(查看集合级读写时间)、MongoDB Atlas(可视化监控)等工具,实时掌握数据库性能状态。db.collection.remove({expireAt: {$lt: new Date()}})),减少数据量对性能的影响。