一、硬件资源优化
二、操作系统层面调优
-n size=64k
(优化命名空间块大小),挂载时添加noatime,nodiratime
(禁用访问时间记录)等选项。deadline
(适合SSD),减少I/O等待时间;通过echo deadline | sudo tee /sys/block/sdX/queue/scheduler
临时生效,修改/etc/udev/rules.d/60-scheduler.rules
永久化。vm.swappiness=5
(降低swap使用,优先利用内存)、vm.dirty_ratio=10
(脏页写入阈值)、vm.dirty_background_ratio=5
(后台脏页写入比例);通过sysctl -p
使配置生效。echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
及defrag
,并添加到/etc/rc.local
永久化。/etc/security/limits.conf
,添加mongodb soft nofile 65536
、mongodb hard nofile 65536
等配置,提升MongoDB处理并发连接的能力。三、MongoDB配置优化
/etc/mongod.conf
中设置storage.wiredTiger.engineConfig.cacheSizeGB
,建议为系统总内存的50%-70%(如16GB内存设置为8GB-12GB),避免占用过多内存影响系统及其他应用。net.port
(默认27017,可根据需求修改)、net.maxIncomingConnections
(如设置为500,提升并发连接数),确保网络带宽充足。storage.journal.enabled=true
(默认开启),保障数据一致性;对于写密集场景,可调整日志缓冲区大小(storage.journal.commitIntervalMs
)以平衡性能与可靠性。四、索引策略优化
find
、sort
、aggregate
的字段创建索引(如db.collection.createIndex({username: 1})
),避免全表扫描。{status: 1, createTime: -1}
),创建复合索引提升查询效率;注意索引字段顺序(将选择性高的字段放在前面)。db.collection.find({status: 1}, {username: 1, _id: 0})
),避免访问磁盘上的文档,减少I/O开销。db.collection.reIndex()
重新构建碎片化索引,提升查询性能;通过db.collection.aggregate([{ $indexStats: {} }])
分析索引使用情况,删除不再使用的索引。五、查询语句优化
find
方法的第二个参数指定返回字段(如db.users.find({}, {username: 1, email: 1, _id: 0})
),减少网络传输量和内存占用。limit()
方法限制查询返回的文档数量(如db.users.find().limit(100)
),避免一次性返回大量数据。explain()
方法分析查询计划(如db.users.find({username: "admin"}).explain("executionStats")
),确保查询使用了索引;若未使用索引,调整索引或查询条件。$match
放在前面过滤数据、$project
减少字段),避免不必要的计算;对于大数据量聚合,考虑使用allowDiskUse: true
(允许使用磁盘临时存储)。六、分片与复制集部署
_id
、时间戳或高频查询字段),避免数据倾斜(如避免使用单调递增的字段作为分片键)。七、监控与诊断
mongostat
(监控操作速率,如读写次数、延迟)、mongotop
(监控集合级别的读写时间)实时查看数据库性能;通过db.serverStatus()
查看内存、连接、索引等详细信息。operationProfiling.slowOpThresholdMs=100
,单位毫秒),通过db.system.profile.find()
查看慢查询详情,针对性优化索引或查询语句。