文档菜单
文档首页
/ / /
Kotlin 同步驱动程序
/ /

组合索引

本页内容

  • 概述
  • 示例数据
  • 创建组合索引
  • 附加信息
  • API 文档

组合索引 存储了集合文档中的多个字段引用,从而提高了查询和排序性能。

当创建复合索引时,必须指定以下内容:

  • 要创建索引的字段

  • 每个字段的排序顺序(升序或降序)

本指南中的示例使用的是movies 集合,该集合位于 sample_mflix 数据库中,来自Atlas 示例数据集。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅Atlas 入门指南

以下 Kotlin 数据类模型表示该集合中的文档

data class Movie(
@BsonId
val id: ObjectId,
val title: String? = "",
val type: String? = "",
val genres: List<String>? = null,
val cast: List<String>? = null,
val plot: String? = "",
)

以下示例在 typegenre 字段上创建复合索引,两个字段均按升序索引

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文档

返回

单字段