使用构建器代码模式
概述
本页介绍了如何在您的代码中使用各种可用的构建器,并描述了使用提供的构建器的优点。
Kotlin 同步驱动程序提供类型安全的构建器类和方法,使开发人员能够高效地构建查询和聚合。
为什么使用构建器?
如果您只使用纯 Kotlin 构建 BSON 查询文档,您无法在运行时识别语法错误。构建器可以帮助确保语法的正确性,并且可能比构建 BSON 文档更简洁。
示例
本节提供了三种获取email
字段值的等效方法,这些值位于满足以下条件的users
集合中的文档
gender
值是"female"
age
值大于29
以下数据类表示users
集合中的文档
data class User( val id: ObjectId, val gender: String, val age: Int, val email: String )
以下数据类表示我们查询返回的结果
data class Email( val email: String )
MongoDB 查询 API
以下示例使用 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)