db.collection.find(query).explain("executionStats")
分析查询是否命中索引,识别低效查询。db.users.createIndex({username: 1})
。db.orders.createIndex({customerId: 1, orderDate: -1, amount: 1})
。db.collection.createIndex({field1: 1, field2: 1})
并查询 {_id: 0, field1: 1, field2: 1}
。db.articles.createIndex({content: "text"})
。db.logs.createIndex({createdAt: 1}, {expireAfterSeconds: 86400})
。db.collection.getIndexes()
查看索引,删除不再使用的索引以减少存储和写入开销。db.collection.reIndex()
重建碎片化索引,提升查询效率(谨慎在高峰期操作)。db.collection.aggregate([{ $indexStats: {} }])
查看索引使用频率和性能。mongostat
和 mongotop
监控索引命中情况和磁盘I/O。/etc/mongod.conf
中设置 wiredTiger.engineConfig.cacheSizeGB
调整缓存大小。operationProfiling
监控慢查询(slowOpThresholdMs: 100
)。sh.shardCollection("db.collection", {shardKey: 1})
。db.collection.find({}, {field1: 1, _id: 0})
。参考来源: