组合索引
概述
组合索引 存储了集合文档中的多个字段引用,从而提高了查询和排序性能。
当创建复合索引时,必须指定以下内容:
要创建索引的字段
每个字段的排序顺序(升序或降序)
示例数据
本指南中的示例使用的是movies
集合,该集合位于 sample_mflix
数据库中,来自Atlas 示例数据集。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅Atlas 入门指南。
以下 Kotlin 数据类模型表示该集合中的文档
data class Movie( val id: ObjectId, val title: String? = "", val type: String? = "", val genres: List<String>? = null, val cast: List<String>? = null, val plot: String? = "", )
创建复合索引
以下示例在 type
和 genre
字段上创建复合索引,两个字段均按升序索引
collection.createIndex(Indexes.ascending(Movie::type.name, Movie::genres.name))
以下是一个使用前面代码示例中创建的索引的查询示例
val filter = and( eq(Movie::type.name, "movie"), `in`(Movie::genres.name, "Drama") ) val sort = Sorts.ascending(Movie::type.name, Movie::genres.name) val results = collection.find(filter).sort(sort) results.forEach { result -> println(result) }
Movie(id=573a1392f29313caabcda755, title=China Seas, type=movie, genres=[Action, Drama, Adventure], ...) Movie(id=573a1392f29313caabcd9ca6, title=Scarface, type=movie, genres=[Action, Crime, Drama], ... ) Movie(id=573a1392f29313caabcdb258, title=The Hurricane, type=movie, genres=[Action, Drama, Romance], ...) Movie(id=573a1391f29313caabcd820b, title=Beau Geste, type=movie, genres=[Action, Adventure, Drama], ...) ...
附加信息
要了解更多有关复合索引的信息,请参阅MongoDB服务器手册中的复合索引。
要了解使用复合索引的有效索引策略,请参阅MongoDB服务器手册中的ESR规则。
API 文档
要了解更多关于本指南中讨论的任何方法,请参阅以下API文档