创建合适的索引
db.collection.createIndex({ field1: 1, field2: -1 })
索引选择性
索引覆盖查询
db.collection.createIndex({ a: 1, b: 1 })
db.collection.find({ a: 5 }, { b: 1, _id: 0 }) // 被索引覆盖
避免全表扫描
explain()
分析查询执行计划db.collection.find({...}).explain("executionStats")
投影优化
db.collection.find({}, { field1: 1, field2: 1 })
分页优化
skip()
和limit()
时配合排序索引合理设计文档结构
读写分离
db.collection.find().readPref("secondary")
分片集群
内存配置
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8
磁盘优化
操作系统优化
批量操作
db.collection.insertMany([doc1, doc2, doc3])
写入关注级别
w:1
(默认)w:"majority"
更新优化
$set
只更新必要字段性能监控
mongostat
和mongotop
db.setProfilingLevel(1, 50) // 记录超过50ms的查询
定期维护
db.collection.reIndex()
db.runCommand({ compact: "collection" })
TTL索引
db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
通过综合应用这些策略,可以显著提升MongoDB的读写性能。实际优化时应根据具体应用场景和负载特点选择合适的策略组合。