Use Builders Code Pattern
On this page
Overview
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.
To learn more about the available builder classes and methods, see the following API documentation sections:
Why Use Builders?
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.
Example
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 than29
The following data class models the documents in the users
collection:
data class User( val id: ObjectId, val gender: String, val age: Int, val email: String )
The following data class models the results returned by the query:
data class Email( val email: String )
MongoDB Query API
The following sample performs the query by using the MongoDB Query API:
collection.find( { "gender": "female", "age" : { "$gt": 29 }}, { "_id": 0, "email": 1 } )
Document Class Filter
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)
In this case, you might easily include an error when writing the
"\$gt"
operator in the filter, but your IDE returns the relevant
error only at runtime.
Builders API
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)
Use Builders with Data Classes
The Use Builders with Data Classes guide provides examples on how to use the preceding builders classes directly with data class properties. This guide might help to make your application more type-safe and improve Kotlin interoperability.