Use Builders Code Pattern
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.
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 our 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)
Builders
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)