MongoDB在Linux中的性能調優技巧
storage.wiredTiger.engineConfig.cacheSizeGB
設置為服務器物理內存的50%-70%(需預留足夠內存給系統和其他進程)。例如,在/etc/mongod.conf
中配置:storage:
wiredTiger:
engineConfig:
cacheSizeGB: 4 # 根據服務器內存調整,如16GB內存可設為8GB
vm.swappiness
(默認60):減少系統使用交換空間(Swap)的傾向,避免內存不足時頻繁換頁導致性能下降。設置為10或更低(sysctl -w vm.swappiness=10
),并添加到/etc/sysctl.conf
持久化。vm.overcommit_memory=1
(允許內存超額分配,但需避免過度使用),同樣添加到/etc/sysctl.conf
。dbpath
)部署在SSD上。noatime
選項(減少文件訪問時間更新):mount -o noatime /dev/sdb1 /var/lib/mongodb
find
、sort
、aggregate
等操作中頻繁使用的字段創建索引。例如,為用戶集合的username
字段創建單字段索引:db.users.createIndex({ username: 1 });
{status: "active", age: {$gt: 18}}
),創建復合索引并將選擇性高的字段放在前面(選擇性高的字段能過濾更多數據)。例如:db.users.createIndex({ status: 1, age: 1 }); // status選擇性更高
db.collection.getIndexes()
查看索引數量,刪除未使用的索引(通過$indexStats
分析)。find({username: "john"}, {username: 1, _id: 0})
),避免訪問實際文檔,減少I/O。db.users.find({}, { username: 1, email: 1, _id: 0 }); // 僅返回username和email
limit()
減少返回的文檔數,避免一次性傳輸大量數據。例如:db.users.find().limit(10); // 只返回前10條
explain()
分析查詢計劃,確保查詢使用了索引。若executionStats.executionStages.stage
顯示為COLLSCAN
(全表掃描),需優化索引。例如:db.users.find({ username: "john" }).explain("executionStats");
bulkWrite
),減少網絡往返次數,提高吞吐量。net.port
(默認27017)和net.maxIncomingConnections
(默認65536,可根據并發連接數調整,如10000)。例如:net:
port: 27017
maxIncomingConnections: 10000
operationProfiling.mode: slowOp
)并設置慢查詢閾值(如100ms),定期分析慢查詢日志優化性能:operationProfiling:
mode: slowOp
slowOpThresholdMs: 100
replication.replSetName
配置副本集(如rs0
),提高數據可用性和讀取性能(可將讀請求分發到從節點)。user_id
)將數據分散到多個分片,提高寫入和查詢的橫向擴展能力。mongostat
(監控操作速率,如讀/寫次數、延遲)和mongotop
(監控集合級別的讀/寫時間)實時查看性能指標。例如:mongostat --host localhost --port 27017
mongotop --host localhost --port 27017
db.collection.reIndex()
重建碎片化索引,提升查詢效率。mongodump
和mongorestore
定期備份,避免數據丟失。