Debian系统中MongoDB性能调优策略
ufw)、禁用SELinux等非必需服务,减少系统资源占用。ulimit配置(如nofile设置为65535以上),扩大文件描述符限制;合理配置swap空间(建议为内存的1-2倍),并通过vm.swappiness参数(设置为10-30)控制内存交换频率。/etc/mongod.conf中的storage.wiredTiger.engineConfig.cacheSizeGB参数,设置为物理内存的50%-70%(避免占用过多内存导致系统不稳定)。net.maxIncomingConnections(如设置为10000以上)和net.maxOutgoingConnections参数,适应高并发连接需求;确保net.bindIp设置为正确的IP地址(如0.0.0.0允许远程访问,但需配合安全组限制)。operationProfiling.mode为slowOp(记录慢查询,默认阈值100ms)或all(记录所有操作),通过systemLog.path指定日志路径(如/var/log/mongodb/mongod.log),便于定位性能瓶颈。_id、username)创建单字段索引(db.collection.createIndex({ field: 1 }));对多字段查询(如{ field1: 1, field2: -1 })创建复合索引,提升查询效率。db.collection.createIndex({ field1: 1, field2: 1 })),使查询可直接从索引中获取数据,避免访问实际文档。reIndex()方法重建碎片化索引(如db.collection.reIndex());通过explain("executionStats")分析查询计划,确认索引使用情况(如winningPlan中是否包含索引)。explain("executionStats")查看查询的执行步骤、索引使用情况及耗时,识别全表扫描(COLLSCAN)等问题。$where、$regex等低效操作符;尽量使用等值查询(=)或范围查询($gt、$lt),提高索引命中率。projection(如db.collection.find({ query }, { field1: 1, field2: 1 }))仅返回必要字段;用limit()(如db.collection.find().limit(10))限制返回文档数量,减少网络传输和内存消耗。bulkWrite()(如db.collection.bulkWrite([{ insertOne: { document: { ... } } }, { updateMany: { filter: { ... }, update: { ... } } }]))替代单条插入/更新,减少网络往返次数。rs.initiate()初始化副本集(如rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "mongo1:27017" }, { _id: 1, host: "mongo2:27017" }] })),实现数据冗余和高可用;将读操作指向次要节点(readPreference: "secondaryPreferred"),减轻主节点压力。sh.enableSharding("database")启用分片,通过sh.shardCollection("database.collection", { shardKey: 1 })按指定字段(如user_id)分片,将数据分散到多个节点,提升读写性能和可扩展性。mongostat(查看每秒查询次数、插入/更新/删除操作数等实时指标)、mongotop(查看集合级别的读写时间分布)监控数据库性能;使用第三方工具(如Percona Monitoring and Management (PMM)、MongoDB Atlas)进行更详细的性能分析和告警。db.collection.deleteMany({ timestamp: { $lt: ISODate("2024-01-01") } } }));使用compact命令压缩集合碎片(如db.runCommand({ compact: "collection" }));及时升级MongoDB版本(如从4.4升级到6.0),获取性能改进和安全修复。