构建器
概述
本节包括如何使用每个可用的构建器的指南,并展示了MongoDB Kotlin驱动程序构建类提供的实用工具。
Kotlin驱动程序提供了类来简化开发人员使用CRUD操作和聚合API的过程。静态实用方法允许您更有效地构建查询。
为什么使用构建器?
使用构建器类,您可以利用
Kotlin编译器和IDE在开发过程中查找错误
IDE进行发现和代码补全
使用构建器时,Kotlin编译器和IDE可以及早捕获诸如拼写错误的运算符之类的错误。当使用MongoDB外壳或纯Kotlin时,您将运算符作为字符串编写,并且没有视觉指示有问题,将这些错误从编译时间推迟到运行时间。
使用构建器类,您将运算符作为方法编写。IDE会立即在右侧下划线并给出红色栏,表明有问题。在开发过程中,IDE还会显示您可以使用的方 法。一旦您选择了想要使用的方法,它就会自动用占位符参数完成您的代码。
场景
假设我们想要向以下条件下的所有用户发送营销邮件users
集合
性别为
female
的用户年龄大于
29
的用户
我们只想获取他们的电子邮件地址,所以我们将确保我们的查询不会返回我们支付带宽费用但不需要的数据。
在应用程序中,我们使用以下数据类来建模 users
集合中的文档。
data class User( val id: BsonObjectId = BsonObjectId(), val gender: String, val age: Int, val email: String, )
使用 MongoDB Shell
collection.find({ "gender": "female", "age" : { "$gt": 29 }}, { "_id": 0, "email": 1 })
不使用 Builders
data class Results(val email: String) val filter = Document().append("gender", "female").append("age", Document().append("\$gt", 29)) val projection = Document().append("_id", 0).append("email", 1) val results = collection.find<Results>(filter).projection(projection)
使用 Builders
import com.mongodb.client.model.Filters import com.mongodb.client.model.Projections
data class Results(val email: String) 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<Results>(filter).projection(projection)