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

使用构建器代码模式

本页内容

  • 概述
  • 为什么使用构建器?
  • 示例
  • MongoDB 查询 API
  • 文档类过滤器
  • 构建器

本页介绍了如何在您的代码中使用各种可用的构建器,并描述了使用提供的构建器的优点。

Kotlin 同步驱动程序提供类型安全的构建器类和方法,使开发人员能够高效地构建查询和聚合。

如果您只使用纯 Kotlin 构建 BSON 查询文档,您无法在运行时识别语法错误。构建器可以帮助确保语法的正确性,并且可能比构建 BSON 文档更简洁。

本节提供了三种获取email字段值的等效方法,这些值位于满足以下条件的users集合中的文档

  • gender值是"female"

  • age值大于29

以下数据类表示users集合中的文档

data class User(
@BsonId val id: ObjectId,
val gender: String,
val age: Int,
val email: String
)

以下数据类表示我们查询返回的结果

data class Email(
val email: String
)

以下示例使用 MongoDB 查询 API 进行查询

collection.find(
{ "gender": "female", "age" : { "$gt": 29 }},
{ "_id": 0, "email": 1 }
)

以下示例使用 Document 类构建查询过滤器进行查询

val filter = Document("gender", "female").append("age", Document("\$gt", 29))
val projection = Document("_id", 0).append("email", 1)
val results = collection.find<Email>(filter).projection(projection)

以下示例使用构建器辅助器进行查询

val filter = Filters.and(
Filters.eq(User::gender.name, "female"),
Filters.gt(User::age.name, 29)
)
val projection = Projections.fields(
Projections.excludeId(),
Projections.include("email")
)
val results = collection.find<Email>(filter).projection(projection)

返回

时间序列