MongoDB在Ubuntu上的性能調優技巧
free -m
查看內存使用情況,根據業務需求調整)。ufw disable
)、禁用SELinux(如setenforce 0
)等,減少系統負載,釋放資源供MongoDB使用。/etc/fstab
中為MongoDB數據目錄添加noatime
參數(如/var/lib/mongodb ext4 defaults,noatime 0 2
),禁止系統更新文件的訪問時間,減少不必要的磁盤寫入。/etc/security/limits.conf
,添加* soft nofile 64000
和* hard nofile 64000
;編輯/etc/systemd/system.conf
,設置DefaultLimitNOFILE=64000
,然后重啟系統生效。/etc/mongod.conf
中的storage.wiredTiger.engineConfig.cacheSizeGB
參數,設置為系統內存的70%-80%(如cacheSizeGB: 4
),控制MongoDB使用的內存上限,避免占用過多系統資源。net.maxIncomingConnections
(默認10000,可根據并發需求增加)和net.maxOutgoingConnections
(默認100,可根據應用需求調整),適應高并發連接場景。operationProfiling
部分設置mode: "slowOp"
和slowOpThresholdMs: 100
(閾值可根據業務調整,如100ms),記錄慢查詢日志,幫助識別性能瓶頸(如未使用索引的查詢)。db.users.createIndex({ username: 1 })
),避免全表掃描。{ username: 1, email: 1 }
),創建復合索引可提升查詢效率,注意將選擇性高的字段(如唯一值多的字段)放在前面。db.users.find({ age: { gt: 18 } }, { name: 1, age: 1, _id: 0 })
),避免回表讀取文檔,減少磁盤I/O。db.collection.reIndex()
重建碎片化索引,提升索引查詢效率;使用db.collection.stats()
分析索引使用情況,刪除不再使用的索引(如db.collection.dropIndex("index_name")
),減少寫操作開銷。db.users.find({ username: "john" })
),避免大范圍查詢(如{ age: { gt: 0 } }
),減少全表掃描。db.users.find({}, { name: 1, email: 1, _id: 0 })
),減少數據傳輸量和內存消耗。skip()
和limit()
進行分頁(如db.users.find().skip(20).limit(10)
),避免一次性獲取大量數據導致內存溢出。match
、group
、sort
)組合在聚合管道中(如db.users.aggregate([{ $match: { age: { gt: 18 } } }, { $group: { _id: "$gender", count: { $sum: 1 } } }])
),減少查詢次數,提升效率。cacheSizeGB: 3
),確保有足夠內存緩存常用數據和索引。zstd
(如storage.wiredTiger.engineConfig.compressor: "zstd"
),但會增加CPU開銷,需根據業務需求權衡。mongostat
監控數據庫操作的速率(如讀寫次數、延遲),mongotop
監控集合級別的讀寫時間(如哪些集合耗時高),快速定位性能瓶頸。explain()
方法(如db.users.find({ username: "john" }).explain("executionStats")
)查看查詢執行計劃,確認是否使用了索引、掃描的文檔數量等,針對性優化查詢。username
字段分片),提升讀寫性能和擴展性。mongodump
和mongorestore
定期備份數據(如每日備份),防止數據丟失(如服務器故障、誤操作)。