第4章:MongoDB索引
4.1 索引基础
4.1.1 索引的重要性
4.1.2 默认索引
{
"_id": ObjectId("..."),
"name": "示例文档"
}
4.2 索引类型
4.2.1 单字段索引
db.users.createIndex({username: 1})
db.users.createIndex({username: -1})
db.users.getIndexes()
4.2.2 复合索引
db.users.createIndex({
lastName: 1,
firstName: 1
})
db.users.find().sort({
lastName: 1,
firstName: 1
})
4.2.3 唯一索引
db.users.createIndex(
{email: 1},
{unique: true}
)
db.users.createIndex(
{username: 1},
{
unique: true,
partialFilterExpression: {age: {$gt: 18}}
}
)
4.2.4 文本索引
db.articles.createIndex(
{content: "text"},
{
weights: {
content: 10,
tags: 5
},
name: "content_text_index"
}
)
db.articles.find({
$text: {$search: "MongoDB 数据库"}
})
4.2.5 地理空间索引
db.places.createIndex({location: "2dsphere"})
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [116.4, 39.9]
},
$maxDistance: 1000
}
}
})
4.3 索引性能分析
4.3.1 查询执行计划
db.users.find({username: "example"}).explain("executionStats")
db.users.find({username: "example"}).hint({username: 1})
4.3.2 索引选择策略
db.products.createIndex({
category: 1,
price: -1
})
db.products.find({
category: "电子产品",
price: {$gt: 1000}
}).sort({price: -1})
4.4 索引管理
4.4.1 索引操作
db.users.dropIndex({username: 1})
db.users.dropIndexes()
db.users.reIndex()
4.4.2 后台创建索引
db.users.createIndex(
{username: 1},
{background: true}
)
4.5 常见索引问题
4.5.1 索引开销
4.5.2 最佳实践
- 仅为常用查询创建索引
- 避免过多索引
- 使用复合索引替代多个单字段索引
- 定期分析和优化