Docs 菜单
Docs 主页
/ / /
Kotlin Sync 驱动程序
/ /

复合索引

在此页面上

  • Overview
  • 样本数据
  • 创建复合索引
  • 更多信息
  • API 文档

复合索引包含对集合文档中多个字段的引用,从而提高查询和排序性能。

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

  • 要在其上创建索引的字段

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

本指南中的示例使用Atlas 样本数据集sample_mflix数据库中的 movies集合。要了解如何创建免费的 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)
}

要了解有关复合索引的更多信息,请参阅 MongoDB Server 手册中的复合索引

要了解使用复合索引的有效索引策略,请参阅 MongoDB Server 手册中的 ESR 规则

要了解有关本指南中讨论的任何方法的更多信息,请参阅以下 API 文档:

后退

单字段索引