// 好的复合索引示例
db.collection.createIndex({ status: 1, createDate: -1 })
// 可优化以下查询
db.collection.find({ status: "active" }).sort({ createDate: -1 })
// 只为活跃用户创建索引
db.users.createIndex(
{ username: 1 },
{ partialFilterExpression: { status: "active" } }
)
// 只为包含email字段的文档创建索引
db.users.createIndex({ email: 1 }, { sparse: true })
// 自动删除30天前的文档
db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 2592000 })
db.collection.find(query).explain("executionStats")
关注关键指标:
- executionTimeMillis
:执行时间
- totalKeysExamined
:检查的索引键数
- totalDocsExamined
:检查的文档数
- stage
:查询阶段(PROJECTION、IXSCAN等)
// 查看集合索引使用情况
db.collection.aggregate([ { $indexStats: {} } ])
// 系统级别索引使用统计
db.serverStatus().metrics.queryExecutor.scanned
opcounters.insert/update/delete
与索引数量的关系db.collection.totalIndexSize()
监控索引大小$indexStats
识别未使用的索引通过合理应用这些策略,可以显著提升MongoDB查询性能,同时避免不必要的资源消耗。