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

使用索引优化查询

本页内容

  • 概述
  • 示例应用
  • 单字段索引
  • 复合索引
  • 多键索引
  • 地理空间索引
  • 唯一索引
  • 通配符索引
  • 聚集索引
  • Atlas 搜索索引管理
  • 创建搜索索引
  • 列出搜索索引
  • 更新搜索索引
  • 删除搜索索引
  • 文本索引
  • 删除索引

在本页中,您可以查看可复制的代码示例,展示如何使用 Kotlin 同步驱动程序管理不同类型的索引。

提示

要了解更多关于索引的信息,请参阅《使用索引》指南。要了解本页面上显示的任何索引的更多信息,请参阅每个部分提供的链接。

要从本页面的示例中获取示例,请将代码示例复制到示例应用程序或您自己的应用程序中。请确保用您MongoDB部署的相关值替换代码示例中的所有占位符,例如<连接字符串URI>

您可以使用以下示例应用程序来测试本页面的代码示例。要使用示例应用程序,请执行以下步骤

  1. 确保您已经在您的Maven或Gradle项目中安装了Kotlin Sync驱动程序。

  2. 复制以下代码并将其粘贴到一个新的.kt文件中。

  3. 从本页面复制一个代码示例并将其粘贴到文件中指定的行。

1import com.mongodb.ConnectionString
2import com.mongodb.MongoClientSettings
3import com.mongodb.client.model.*
4import com.mongodb.kotlin.client.*
5import org.bson.Document
6
7fun main() {
8 val uri = "<connection string URI>"
9
10 val settings = MongoClientSettings.builder()
11 .applyConnectionString(ConnectionString(uri))
12 .retryWrites(true)
13 .build()
14
15 // Create a new client and connect to the server
16 val mongoClient = MongoClient.create(settings)
17 val database = mongoClient.getDatabase("<database name>")
18 val collection = database.getCollection<Document>("<collection name>")
19
20 // Start example code here
21
22 // End example code here
23}

以下示例在指定的字段上创建一个升序索引

collection.createIndex(Indexes.ascending("<field name>"))

要了解更多关于单字段索引的信息,请参阅单字段索引指南。

以下示例在指定的字段上创建复合索引

collection.createIndex(Indexes.ascending("<field name 1>", "<field name 2>"))

要了解更多关于复合索引的信息,请参阅复合索引指南。

以下示例在指定的数组值字段上创建多键索引

collection.createIndex(Indexes.ascending("<array field name>"))

以下示例在包含GeoJSON对象的指定字段上创建2dsphere索引

collection.createIndex(Indexes.geo2dsphere("<GeoJSON object field>"))

以下示例在指定的字段上创建唯一索引

val indexOptions = IndexOptions().unique(true)
collection.createIndex(Indexes.ascending("<field name>"), indexOptions)

以下示例在指定集合中创建通配符索引

collection.createIndex(Indexes.ascending("$**"))

以下示例在 _id 字段上创建一个新的集合并设置聚集索引

val clusteredIndexOptions = ClusteredIndexOptions(
Indexes.ascending("_id"),
true
)
val collection = database.createCollection("<collection name>", clusteredIndexOptions)

以下部分包含代码示例,说明如何管理 Atlas Search 索引。

有关 Atlas Search 索引的更多信息,请参阅Atlas Search 和向量搜索索引指南。

以下示例在指定的字段上创建Atlas Search索引。

val index = Document("mappings", Document("dynamic", true))
collection.createSearchIndex("<index name>", index)

要了解更多关于创建搜索索引的信息,请参阅创建搜索索引指南。

以下示例打印指定集合中Atlas Search索引的列表。

val results = collection.listSearchIndexes()
results.forEach { result ->
println(result)
}

要了解更多关于列出搜索索引的信息,请参阅列出搜索索引指南。

以下示例使用指定的新索引定义更新现有的Atlas Search索引。

val newIndex = Document("mappings", Document("dynamic", true))
collection.updateSearchIndex("<index name>", newIndex)

要了解更多关于更新搜索索引的信息,请参阅更新搜索索引指南。

以下示例展示了如何删除具有指定名称的Atlas Search索引

collection.dropIndex("<index name>")

要了解更多关于删除搜索索引的信息,请参阅删除搜索索引指南。

以下示例展示了如何在指定的字符串字段上创建文本索引

collection.createIndex(Indexes.text("<field name>"))

以下示例展示了如何删除具有指定名称的索引

collection.dropIndex("<index name>")

返回

监控数据更改