storage.wiredTiger.engineConfig.cacheSizeGB
設置為系統物理內存的50%-80%(如8GB內存可設為4-6GB),確保常用數據和索引緩存在內存中,減少磁盤I/O。/etc/default/grub
,添加GRUB_CMDLINE_LINUX_DEFAULT="quiet numa=off transparent_hugepage=never"
;sudo grub-mkconfig -o /boot/grub/grub.cfg
更新GRUB,重啟系統使配置生效。vm.swappiness
參數(如sudo sysctl vm.swappiness=10
,值越低越傾向于使用物理內存),避免內存不足時頻繁換頁導致性能下降。ufw disable
)、SELinux等非必需服務,減少系統負載。/etc/mongod.conf
中的bindIp
(如設為0.0.0.0
允許遠程訪問,或指定具體IP增強安全性),確認port
(默認27017)未被其他服務占用。security.authorization: enabled
,強制用戶認證,防止未授權訪問導致的安全風險。systemLog.path
(如/var/log/mongodb/mongod.log
)記錄操作日志,設置logAppend: true
避免日志覆蓋;通過operationProfiling.mode
設置為slowOp
(默認100ms)或all
,監控慢查詢。replication.replSetName: "rs0"
,后續通過rs.initiate()
初始化副本集,提升讀取性能和數據冗余。_id
、username
、timestamp
)創建索引,使用db.collection.createIndex({ field: 1 })
(1表示升序,-1表示降序)。{ field1: 1, field2: -1 }
),創建復合索引,避免多次索引掃描。db.collection.find({ field1: 1 }, { field1: 1, _id: 0 }).explain("executionStats")
),使查詢直接從索引獲取數據,無需訪問文檔。reIndex()
重建碎片化索引,優化索引效率。explain("executionStats")
查看查詢的執行計劃,確認是否使用了索引(winningPlan
中的IXSCAN
表示索引掃描),避免全表掃描。limit()
減少返回文檔數量(如db.collection.find().limit(10)
),降低網絡傳輸和內存消耗。bulkWrite()
進行批量插入、更新或刪除,減少網絡往返次數(如批量插入1000條文檔比單條插入效率高得多)。updateMany()
時添加查詢條件(如db.collection.updateMany({ status: "active" }, { $set: { lastLogin: new Date() } })
),避免鎖定整個集合。user_id
分片),提升讀寫性能和可擴展性。需先啟用分片(sh.enableSharding("database")
),再對集合進行分片(sh.shardCollection("database.collection", { shardKey: 1 })
)。mongostat
監控每秒查詢次數(QPS)、寫入延遲等實時指標;mongotop
查看各集合的讀寫時間分布,快速定位熱點表。compact
命令回收未使用的存儲空間(如db.runCommand({ compact: "collectionName" })
);定期備份數據(使用mongodump
),防止數據丟失。