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版本(獲取性能改進和安全修復)。