对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

将构建器与数据类结合使用

重要

本页描述的功能仅在Kotlin驱动程序版本 5.3 或更高版本中可用。

在本指南中,您可以学习如何将数据类属性直接与Kotlin驱动程序中提供的构建者类一起使用。

Kotlin驱动程序实现了一些扩展,允许您在使用构建者方法(而不是使用string字段名称)时引用数据类属性。您可以通过这种方式构建代码,从而提高代码的类型安全性,并提高应用程序的Kotlin互操作性。

The extensions library also allows you to construct queries, update documents, and write other statements by using infix notation. To learn more about this notation, see Infix notation in the Kotlin reference documentation.

注意

本页提供了有限数量的代码示例来演示此功能。 要查看所有构建器类的示例,请参阅构建器指南。

要实现此功能,您必须将 mongodb-driver-kotlin-extensions 依赖项添加到依赖项列表中。

提示

物料清单

我们建议将Java虚拟机(JVM)驱动程序物料清单 (BOM) 添加到您的应用程序中,以管理驱动程序工件的版本。这删除了为 BOM 涵盖的任何单个包指定版本的需要,从而简化了依赖项管理。要学习;了解更多信息,请参阅快速入门指南中的“添加驱动程序物料清单”步骤。

从以下标签页中进行选择,查看如何使用 GradleMaven包管理器将扩展依赖项添加到项目中:

If you are using Gradle to manage your dependencies, add the following to your build.gradle.kts dependencies list:

build.gradle.kts
implementation("org.mongodb:mongodb-driver-kotlin-extensions")

If you are using Maven to manage your dependencies, add the following to your pom.xml dependencies list:

pom.xml
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-kotlin-extensions</artifactId>
</dependency>

After you install the extensions dependency, you can use the extension methods by importing classes and methods from the com.mongodb.kotlin.client.model path. You can mix usage of these methods and the standard builder methods in the same application, as shown in the Aggregates example in this guide.

本节包含的示例演示如何将数据类属性直接与扩展包中的构建器类方法一起使用。

提示

数据类注解

当您使用数据类的扩展构建器类方法时,这些方法会遵循 bson-kotlinbson-kotlinx 包中的数据类注解。要学习;了解有关注解的更多信息,请参阅《文档数据格式:数据类》指南中的“使用注解指定组件转换”部分和《Kotlin序列化指南》中的“注解数据类”部分。

本部分中的示例使用 students集合中描述学校学生的文档。students集合中的文档由以下Kotlin数据类进行建模:

data class Student(
val name: String,
val teachers: List<String>,
val gradeAverage: Double
)

您可以使用 Filters构建者类中的助手来查询数据类属性。要学习;了解有关此类的更多信息,请参阅 筛选器构建器指南。

以下代码展示了使用 Filters 扩展方法对 Student 数据类执行查询的不同方法:

import com.mongodb.kotlin.client.model.Filters.eq
import com.mongodb.kotlin.client.model.Filters.all
val student = Student(
"Sandra Nook",
listOf("Alvarez", "Gruber"),
85.7
)
// Equivalent equality queries
Student::name.eq(student.name)
eq(Student::name, student.name)
Student::name eq student.name // Infix notation
// Equivalent array queries
all(Student::teachers, student.teachers)
Student::teachers.all(student.teachers)
Student::teachers all student.teachers // Infix notation

您可以使用 Indexes构建者类中的助手为数据类属性创建索引。 要学习;了解有关此类的更多信息,请参阅 索引构建器指南。

以下代码展示了使用 Indexes 扩展方法在 Student 数据类上创建索引的不同方法:

import com.mongodb.kotlin.client.model.Indexes.ascending
import com.mongodb.kotlin.client.model.Indexes.descending
val ascendingIdx = Indexes.ascending(Student::name)
val descendingIdx = Indexes.descending(Student::teachers)
val ascIdxName = collection.createIndex(ascendingIdx)
val descIdxName = collection.createIndex(descendingIdx)

您可以使用 Projections构建者类中的助手为数据类属性创建投影。要学习;了解有关此类的更多信息,请参阅 投影生成器指南。

以下代码展示了如何使用 Projections 扩展方法在 Student 数据类上创建投影:

import com.mongodb.kotlin.client.model.Projections.excludeId
import com.mongodb.kotlin.client.model.Projections.fields
import com.mongodb.kotlin.client.model.Projections.include
val combinedProj = fields(
include(Student::name, Student::gradeAverage),
excludeId()
)
collection.find().projection(combinedProj)

您可以使用 Sorts构建者类中的助手对数据类属性进行排序。 要学习;了解有关此类的更多信息,请参阅 排序构建器指南。

以下代码演示如何使用 Sorts 扩展方法对 Student 数据类创建不同的排序:

import com.mongodb.client.model.Sorts.orderBy
import com.mongodb.kotlin.client.model.Sorts
val sort = orderBy(
Sorts.descending(Student::gradeAverage),
Sorts.ascending(Student::name)
)
collection.find().sort(sort)

您可以使用 Updates构建者类中的助手,通过数据类属性执行更新。要学习;了解有关此类的更多信息,请参阅 Updates Builders指南。

以下代码演示如何使用 Sorts 扩展方法对 Student 数据类创建不同的排序:

import com.mongodb.kotlin.client.model.Filters.gte
import com.mongodb.kotlin.client.model.Updates.addToSet
import com.mongodb.kotlin.client.model.Updates.combine
import com.mongodb.kotlin.client.model.Updates.max
val filter = Student::gradeAverage gte 85.0
val update = combine(
addToSet(Student::teachers, "Soto"),
Student::gradeAverage.max(90.0)
)
collection.updateMany(filter, update)

您可以使用 AggregatesAccumulators构建者类中的助手,通过数据类属性来执行聚合。要学习;了解有关这些类的更多信息,请参阅 聚合构建器指南。

以下代码展示了如何使用 Accumulators 扩展方法和 Aggregates 辅助方法对 Student 数据类执行聚合:

import com.mongodb.client.model.Aggregates.group
import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.sort
import com.mongodb.kotlin.client.model.Accumulators.avg
// Data class to store aggregation result
data class Summary ( val average: Double )
val pipeline = listOf(
// Sorts grades from high to low
sort(Sorts.descending(Student::gradeAverage)),
// Selects the top 3 students
limit(3),
// Calculates the average of their grades and stores value in a Summary instance
group(null, avg(Summary::average, "\$${Student::gradeAverage.name}"))
)
val result = collection.aggregate<Summary>(pipeline)