Docs Menu

Docs HomeKotlin Coroutine

Builders

On this page

  • Overview
  • Why Use Builders?
  • Scenario
  • Using the MongoDB Shell
  • Without Using Builders
  • Using Builders
  • Available Builders

This section includes guides on how to use each of the available builders, and demonstrates the utility the MongoDB Kotlin driver builder classes provide.

The Kotlin driver provides classes to simplify the process for developers to use CRUD operations and the Aggregation API. The static utility methods allow you to build a query more efficiently.

Using the builders class, you leverage the power of:

  • The Kotlin compiler and the IDE to find errors during development

  • The IDE for discovery and code completion

When using builders, the Kotlin compiler and the IDE catch errors such as misspelled operators early on. When using the MongoDB shell or plain Kotlin, you write operators as strings and get no visual indication of a problem, pushing these errors to runtime instead of compile time.

With the builder classes, you write operators as methods. The IDE instantly underlines and gives you a red bar on the right indicating something is wrong. While developing, the IDE also shows you the methods you can use. It automatically completes your code with placeholder parameters once you select which method you want to use.

Imagine we want to send a marketing email to all users in our users collection with the following criteria:

  • Users that identify as female gender

  • Users that are older than 29

We only want their email address, so we'll ensure our query doesn't return data we pay bandwidth costs for but don't need.

The documents in the users collection are modeled with the following data class in our application:

data class User(
@BsonId
val id: BsonObjectId = BsonObjectId(),
val gender: String,
val age: Int,
val email: String,
)
collection.find({ "gender": "female", "age" : { "$gt": 29 }}, { "_id": 0, "email": 1 })
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)
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)
←  Compound OperationsAggregates Builders →