索引类型与创建
约 529 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › MongoDB › 索引与聚合(在新窗口打开) › 索引类型与创建
索引基础
// 查看集合的所有索引
db.users.getIndexes()
// 默认有 _id_ 唯一索引
// 创建单字段索引
db.users.createIndex({ name: 1 }) // 1 升序,-1 降序
// 删除索引
db.users.dropIndex("name_1")
db.users.dropIndex({ name: 1 })复合索引
// 创建复合索引(ESR 原则:等值 → 排序 → 范围)
db.users.createIndex({ status: 1, age: -1, createdAt: 1 })ESR 原则:
| 顺序 | 字段 | 条件类型 |
|---|---|---|
| E (Equality) | status: 1 | status: "active" |
| S (Sort) | age: -1 | sort({ age: -1 }) |
| R (Range) | createdAt: 1 | createdAt: { $gt: ... } |
唯一索引
// 单字段唯一
db.users.createIndex({ email: 1 }, { unique: true })
// 复合唯一
db.users.createIndex({ firstName: 1, lastName: 1 }, { unique: true })
// 稀疏唯一(允许缺失字段)
db.users.createIndex({ phone: 1 }, { unique: true, sparse: true })多键索引
数组字段上的索引自动为多键索引:
// 自动成为多键索引
db.users.createIndex({ tags: 1 })
// 查询时会为数组的每个元素建立索引条目
db.users.find({ tags: "developer" })文本索引
// 创建文本索引
db.articles.createIndex({ title: "text", body: "text" })
// 文本搜索
db.articles.find({
$text: { $search: "mongodb index" }
})
// 文本搜索 + 相关性排序
db.articles.find(
{ $text: { $search: "mongodb performance" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })TTL 索引
文档自动过期删除:
// 60 秒后自动删除
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 60 }
)
// 插入文档
db.sessions.insertOne({
sessionId: "abc123",
createdAt: new Date()
})
// 60 秒后自动删除索引属性
// 后台创建(不阻塞读写)
db.users.createIndex({ name: 1 }, { background: true })
// 隐藏索引(测试删除索引的影响,但不实际删除)
db.users.createIndex({ age: 1 }, { hidden: true })
db.users.hideIndex("age_1")
db.users.unhideIndex("age_1")
// 部分索引(只索引满足条件的文档)
db.users.createIndex(
{ status: 1 },
{ partialFilterExpression: { status: { $exists: true } } }
)小结
- 单字段索引:
createIndex({ field: 1 });复合索引:createIndex({ a: 1, b: -1 })。 - ESR 原则:等值字段在前,排序字段在中,范围字段在后。
- 特殊索引:
unique: true保证字段唯一;文本索引做全文搜索;TTL 索引自动过期。 - 数组字段自动创建多键索引。
hidden: true测试删除索引影响;background: true后台建索引。
上一节:删除文档 下一节:explain 与查询优化
