在Ubuntu上優化MongoDB查詢速度可從以下方面入手:
vm.swappiness
)減少磁盤I/O。/etc/mongod.conf
中設置storage.wiredTiger.engineConfig.cacheSizeGB
,建議為可用內存的50%-70%。operationProfiling
監控慢查詢(閾值可設為100ms)。// 復合索引示例(覆蓋查詢需求)
db.users.createIndex({ status: 1, age: -1, name: 1 });
reIndex()
重建碎片化索引,刪除冗余索引。$or
、$ne
等低效操作。skip()
和limit()
分頁,通過投影({ field: 1, _id: 0 }
)減少返回字段。$match
)、排序($sort
)等操作前置,利用索引加速。mongostat
、mongotop
或第三方工具(如PMM)實時監控性能。explain("executionStats")
定位低效查詢,針對性優化。mongodump
備份數據,升級到最新穩定版本以獲取性能改進。注意:優化前需在測試環境驗證效果,避免生產環境直接調整。優先通過索引和查詢重構提升性能,再考慮硬件升級。