Ubuntu環境下MongoDB性能調優技巧
storage.wiredTiger.engineConfig.cacheSizeGB參數設置)。例如,16GB內存服務器可設置cacheSizeGB: 10(約占62.5%),避免占用過多內存影響系統及其他應用。storage.journal.enabled: true)以保證數據持久性。vm.nr_hugepages=0參數),避免內存碎片化;調整vm.swappiness=0(降低交換分區使用概率),提升內存利用率。/etc/mongod.conf中,通過net.maxIncomingConnections設置最大連接數(如net.maxIncomingConnections: 1000),避免連接數過多導致資源耗盡;根據網絡帶寬調整net.bufferSize(默認16MB,高帶寬環境可適當增大)。storage.wiredTiger.engineConfig.journalCompressor(日志壓縮)、storage.wiredTiger.collectionConfig.blockCompressor(集合數據壓縮)進一步優化存儲效率。operationProfiling模塊開啟慢查詢日志,設置slowOpThresholdMs(如slowOpThresholdMs: 100,單位毫秒),記錄執行時間超過閾值的查詢,便于后續分析與優化。where、sort、join條件中的字段)創建索引,例如db.users.createIndex({age: 1})(升序索引)。復合索引需根據查詢模式設計字段順序(如db.users.createIndex({status: 1, age: -1}),適用于status篩選后按age降序查詢的場景)。db.collection.reIndex()重建索引,清理碎片(尤其在高寫入負載場景下);通過db.collection.stats()查看索引大小與使用情況,刪除未使用索引(db.collection.explain("executionStats").find({...}).executionStats.executionStages.inputStage.stage顯示IXSCAN的索引才是有效索引)。db.users.find({name: "John"}, {name: 1, _id: 0})配合db.users.createIndex({name: 1}))。explain("executionStats")分析查詢計劃,避免全表掃描(winningPlan.stage為COLLSCAN);確保查詢條件能利用索引(如db.users.find({age: {$gt: 18}}).explain()應顯示IXSCAN)。db.users.find({age: {$gt: 18}}, {name: 1, age: 1, _id: 0})(不返回_id字段),降低網絡傳輸壓力。skip()與limit()進行分頁(如db.users.find().skip(20).limit(10)),避免一次性獲取大量數據;采用insertMany()(批量插入)、updateMany()(批量更新)替代單條操作,減少網絡往返次數。user_id、order_id等高基數字段),避免熱點問題(如{timestamp: 1}可能導致寫入集中在最新分片)。sh.shardCollection("db.collection", {shardKey: 1})手動分片;監控分片集群的chunk分布(sh.status()),確保數據均勻分布。mongostat(監控每秒操作數、讀寫延遲)、mongotop(監控集合級讀寫時間)實時查看數據庫性能。db.collection.validate()檢查數據完整性;每月清理無用數據(如過期日志、臨時集合);每季度評估索引策略(根據查詢模式變化調整索引)。