Debian系统下MongoDB性能调优方法
/etc/default/grub文件,添加GRUB_CMDLINE_LINUX_DEFAULT="quiet numa=off transparent_hugepage=never",禁用NUMA(非一致性内存访问)和Transparent Hugepage(透明巨页),避免内存分配延迟,修改后运行sudo grub-mkconfig -o /boot/grub/grub.cfg更新GRUB并重启系统。/etc/mongod.conf文件,设置storage.dbPath为数据存储目录(确保足够磁盘空间);net.bindIp根据需求绑定IP(如0.0.0.0允许远程访问,或指定具体IP增强安全性);systemLog.path指定日志文件路径(便于故障排查);processManagement.fork设为true,让MongoDB以后台守护进程运行。storage.engine: wiredTiger;storage.wiredTiger.engineConfig.cacheSizeGB根据服务器内存大小调整(建议为物理内存的50%-70%,如16GB内存可设为8GB);storage.wiredTiger.collectionConfig.blockCompressor选择压缩算法(snappy为默认,平衡压缩率与CPU开销;zlib压缩率更高但消耗更多CPU);storage.journal.enabled设为true(启用日志保证数据持久性),commitIntervalMs调整为100(缩短日志提交间隔,提升写入性能)。operationProfiling.mode: slowOp(记录超过默认100ms的慢查询),或operationProfiling.mode: all(记录所有操作,用于详细分析),operationProfiling.slowOpThresholdMs可根据业务需求调整(如50ms)。find、sort、update操作的字段创建索引,如db.collection.createIndex({ field: 1 })(1表示升序,-1表示降序);对于多字段查询,使用复合索引(如db.collection.createIndex({ field1: 1, field2: -1 })),注意索引顺序需匹配查询条件。explain("executionStats")分析查询执行计划(如db.collection.find({ field: 1 }).explain("executionStats")),查看winningPlan中的indexName字段,确认是否使用了索引;若executionTimeMillis过高,需调整索引或查询语句。reIndex()方法重建索引(如db.collection.reIndex()),消除索引碎片,提升查询效率。db.collection.find({ field1: 1 }, { _id: 0, field1: 1, field2: 1 })),减少网络传输和内存消耗;避免在查询条件中使用正则表达式(如/abc/)和全表扫描操作(如无索引的$where子句),尽量使用精确匹配或范围查询。bulkWrite()方法进行批量插入、更新或删除(如db.collection.bulkWrite([{ insertOne: { document: { field: 1 } } }, { updateMany: { filter: {}, update: { $set: { field: 2 } } } }])),减少客户端与服务器之间的网络往返次数,提升吞吐量。limit()方法限制返回的文档数量(如db.collection.find({ field: 1 }).limit(10)),避免一次性返回大量数据导致内存溢出。rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "host1:27017" }, { _id: 1, host: "host2:27017" }, { _id: 2, host: "host3:27017" }] })),其中host1、host2、host3为副本集节点地址;复制集自动同步数据,读操作可分发到从节点,减轻主节点压力。sh.enableSharding("databaseName")),对集合进行分片(sh.shardCollection("databaseName.collectionName", { shardKey: 1 })),其中shardKey需选择高基数、均匀分布的字段(如用户ID、时间戳),避免数据倾斜。mongostat监控数据库操作统计(如每秒查询次数、插入次数、更新次数,mongostat --host localhost --port 27017);使用mongotop查看热点表(即哪些集合或索引消耗最多时间,mongotop --host localhost --port 27017)。db.setProfilingLevel(1, 50)开启慢查询记录(1表示记录慢查询,50表示慢查询阈值为50ms),慢查询日志存储在system.profile集合中,可使用db.system.profile.find().sort({ ts: -1 }).limit(10)查看最近的慢查询,针对性优化。