Docs Menu
Docs Home
/ / /
Kotlin Sync Driver

Use Builders Code Pattern

On this page

  • Overview
  • Why Use Builders?
  • Example
  • MongoDB Query API
  • Document Class Filter
  • Builders

This page describes how to use the various available builders in your code and describes benefits of using the provided builders.

The Kotlin Sync driver provides type-safe builder classes and methods that enable developers to efficiently build queries and aggregations.

If you use only plain Kotlin to construct BSON query documents, you are not able to identify syntax errors until runtime. The builders help ensure the corretness of syntax and can be less verbose than constructing BSON documents.

This section provides three equivalent ways to fetch the email field values of documents in the users collection that meet the following criteria:

  • gender value is "female"

  • age value is greater than 29

The following data class models the documents in the users collection:

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

The following data class models the results returned by our query:

data class Email(
val email: String
)

The following sample performs the query by using the MongoDB Query API:

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

The following example performs the query by using the Document class to construct the query filter:

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)

The following example performs the query by using the builder helpers:

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)

Back

Time Series