参考答案:
在 MongoDB 中,索引是一个数据结构,它用于提高数据库查询的效率。通过在一个或多个字段上创建索引,MongoDB 可以快速地查找匹配的文档,而无需扫描整个集合。索引是关系型数据库和非关系型数据库中常见的优化机制,用于加速数据检索。
索引的基本概念:
索引的创建和查找:
单字段索引(Single Field Index):
1db.collection.createIndex({ fieldName: 1 }) // 升序索引 2db.collection.createIndex({ fieldName: -1 }) // 降序索引
复合索引(Compound Index):
1db.collection.createIndex({ field1: 1, field2: -1 })
field1
升序和 field2
降序创建的,适用于 field1
和 field2
都作为查询条件的场景。多键索引(Multikey Index):
tags
,你可以为该字段创建一个多键索引来加速基于数组元素的查询。1db.collection.createIndex({ tags: 1 })
哈希索引(Hashed Index):
1db.collection.createIndex({ fieldName: "hashed" })
fieldName
等于某个特定值的查询。地理空间索引(Geospatial Index):
1db.collection.createIndex({ location: "2dsphere" })
文本索引(Text Index):
1db.collection.createIndex({ fieldName: "text" })
$text
查询来进行全文搜索:
1db.collection.find({ $text: { $search: "keyword" } })
唯一索引(Unique Index):
email
字段。1db.collection.createIndex({ fieldName: 1 }, { unique: true })
提高查询效率:
提高排序效率:
减少 I/O 开销:
最近更新时间:2024-12-23