查看所有索引
// 查看集合的所有索引
db.collection('yourCollection').getIndexes()
// 使用 indexes() 方法(等效)
db.collection('yourCollection').indexes()
创建索引
// 创建单字段索引(升序)
db.collection('users').createIndex({ email: 1 })
// 创建单字段索引(降序)
db.collection('users').createIndex({ age: -1 })
// 创建复合索引
db.collection('orders').createIndex({ customerId: 1, orderDate: -1 })
// 创建唯一索引
db.collection('users').createIndex({ email: 1 }, { unique: true })
// 创建稀疏索引(只索引存在该字段的文档)
db.collection('users').createIndex({ phoneNumber: 1 }, { sparse: true })
// 创建 TTL 索引(文档自动过期删除)
db.collection('sessions').createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
// 创建文本索引(全文搜索)
db.collection('articles').createIndex({ content: "text", title: "text" })
// 创建地理空间索引
db.collection('locations').createIndex({ coordinates: "2dsphere" })
删除索引
// 删除指定名称的索引
db.collection('users').dropIndex("email_1")
// 删除指定字段的索引
db.collection('users').dropIndex({ email: 1 })
// 删除所有索引(_id 索引除外)
db.collection('users').dropIndexes()
// 删除多个指定的索引
db.collection('users').dropIndexes(["email_1", "age_-1"])
查看索引统计信息
// 查看索引使用统计
db.collection('users').aggregate([{ $indexStats: {} }])
// 查看集合统计信息(包括索引大小)
db.collection('users').stats()
// 查看特定索引的大小
db.collection('users').stats().indexSizes
重建索引
// 重建所有索引
db.collection('users').reIndex()
// 注意:reIndex() 会锁定集合,在生产环境中慎用
查看查询的索引使用情况
// 使用 explain() 查看查询计划
db.collection('users').find({ email: "[email protected]" }).explain("executionStats")
// 查看聚合管道的索引使用
db.collection('orders').aggregate([
{ $match: { customerId: "12345" } },
{ $sort: { orderDate: -1 } }
]).explain("executionStats")
创建后台索引
// 在后台创建索引(不阻塞其他操作)
db.collection('users').createIndex({ email: 1 }, { background: true })
// 注意:从 MongoDB 4.2 开始,所有索引构建都使用优化的算法
部分索引
// 创建部分索引(只索引符合条件的文档)
db.collection('users').createIndex(
{ email: 1 },
{
partialFilterExpression: {
age: { $gte: 18 }
}
}
)
// 部分唯一索引
db.collection('users').createIndex(
{ email: 1 },
{
unique: true,
partialFilterExpression: {
email: { $exists: true }
}
}
)
隐藏索引
// 隐藏索引(用于测试删除索引的影响)
db.collection('users').hideIndex("email_1")
// 取消隐藏索引
db.collection('users').unhideIndex("email_1")
索引最佳实践