MongoDB在Ubuntu上的查詢優化策略
free -m
命令查看內存使用情況。ulimit -n
),避免大量連接導致資源耗盡。編輯/etc/mongod.conf
文件,調整關鍵參數:
net.maxIncomingConnections
(默認10000,可根據需求增減);storage.wiredTiger.engineConfig.cacheSizeGB
為物理內存的50%-70%(避免占用過多內存導致系統交換);operationProfiling.mode: "slowOp"
并設置slowOpThresholdMs
(如100ms),監控慢查詢。username
、email
)創建單字段索引(db.users.createIndex({ username: 1 })
);對多字段查詢(如同時查username
和email
)使用復合索引(db.users.createIndex({ username: 1, email: 1 })
);db.users.find({ age: { gt: 18 } }, { name: 1, age: 1, _id: 0 })
),避免回表查詢;db.collection.reIndex()
重建碎片化索引;通過db.collection.explain("executionStats").find()
分析查詢計劃,確認索引是否被有效使用;刪除未使用的冗余索引(減少寫操作開銷)。db.users.find({}, { name: 1, email: 1 })
),減少數據傳輸量和內存消耗;skip()
和limit()
分頁(如db.users.find().skip(20).limit(10)
),避免一次性加載過多數據;{}
),盡量使用具體值或范圍查詢(如{ age: { gt: 18 } }
);db.users.createIndex({ age: 1 })
),提升排序性能;match
+group
)組合成聚合管道(db.users.aggregate([{ $match: { age: { gt: 18 } } }, { $group: { _id: "$gender", count: { $sum: 1 } } }])
),減少查詢次數。mongostat
監控數據庫操作的吞吐量(如讀寫次數/秒)、mongotop
查看集合級別的讀寫時間分布(定位慢查詢集合);explain("executionStats")
查看查詢的執行計劃(如是否使用索引、掃描文檔數、執行時間),針對性優化;{ user_id: 1, orders: [{ product: "A", price: 100 }] }
),減少JOIN操作;username
復制到訂單集合),減少跨集合查詢次數。user_id
分片),分散查詢負載;compact
命令壓縮數據文件(減少磁盤空間占用)、repairDatabase
修復損壞的數據文件(避免性能退化);