Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/ /

Use Builders with Data Classes

On this page

  • Overview
  • Add Kotlin Extensions to Your Project
  • Builders Examples
  • Sample Data
  • Filters
  • Indexes
  • Projections
  • Sorts
  • Updates
  • Aggregates
  • API Documentation

In this guide, you can learn how to use your data class properties directly with the builder classes available in the Kotlin driver.

The Kotlin driver implements extensions that allow you to reference your data class properties when using builder methods instead of using string field names. You can structure your code in this way to make your code more type-safe and improve your applications Kotlin interoperability.

The extensions library also allows you to construct queries, update documents, and write other statements by using infix notation. To learn more about this notation, see Infix notation in the Kotlin reference documentation.

Note

This page provides a limited number of code examples to demonstrate this functionality. To view examples for all the builder classes, see the Builders guides.

To implement this functionality, you must add the mongodb-driver-kotlin-extensions dependency to your dependencies list.

Select from the following tabs to see how to add the extension dependency to your project by using the Gradle and Maven package managers:

If you are using Gradle to manage your dependencies, add the following to your build.gradle.kts dependencies list:

build.gradle.kts
implementation("org.mongodb:mongodb-driver-kotlin-extensions:5.3.0")

If you are using Maven to manage your dependencies, add the following to your pom.xml dependencies list:

pom.xml
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-kotlin-extensions</artifactId>
<version>5.3.0</version>
</dependency>

After you install the extensions dependency, you can use the extension methods by importing classes and methods from the com.mongodb.kotlin.client.model path. You can mix usage of these methods and the standard builder methods in the same application, as shown in the Aggregates example in this guide.

This section contains examples that demonstrate how to use data class properties directly with builder class methods from the extensions package.

Tip

Data Class Annotations

When you the extension builder class methods data classes, the methods respect your data class annotations from the bson-kotlin and bson-kotlinx packages. To learn more about annotations, see the Specify Component Conversion Using Annotations section of the Document Data Format: Data Classes guide and the Annotate Data Classes section in the Kotlin Serialization guide.

The examples in this section use documents in the students collection that describe students at a school. Documents in the students collection are modeled by the following Kotlin data class:

data class Student(
val name: String,
val teachers: List<String>,
val gradeAverage: Double
)

You can use helpers from the Filters builders class to query on data class properties. To learn more about this class, see the Filters Builders guide.

The following code shows different ways to use Filters extension methods to perform queries on the Student data class:

import com.mongodb.kotlin.client.model.Filters.eq
import com.mongodb.kotlin.client.model.Filters.all
val student = Student(
"Sandra Nook",
listOf("Alvarez", "Gruber"),
85.7
)
// Equivalent equality queries
Student::name.eq(student.name)
eq(Student::name, student.name)
Student::name eq student.name // Infix notation
// Equivalent array queries
all(Student::teachers, student.teachers)
Student::teachers.all(student.teachers)
Student::teachers all student.teachers // Infix notation

You can use helpers from the Indexes builders class to create indexes on data class properties. To learn more about this class, see the Indexes Builders guide.

The following code shows different ways to use Indexes extension methods to create indexes on the Student data class:

import com.mongodb.kotlin.client.model.Indexes.ascending
import com.mongodb.kotlin.client.model.Indexes.descending
val ascendingIdx = Indexes.ascending(Student::name)
val descendingIdx = Indexes.descending(Student::teachers)
val ascIdxName = collection.createIndex(ascendingIdx)
val descIdxName = collection.createIndex(descendingIdx)

You can use helpers from the Projections builders class to create projections for data class properties. To learn more about this class, see the Projections Builders guide.

The following code shows how to use Projections extension methods to create a projection on the Student data class:

import com.mongodb.kotlin.client.model.Projections.excludeId
import com.mongodb.kotlin.client.model.Projections.fields
import com.mongodb.kotlin.client.model.Projections.include
val combinedProj = fields(
include(Student::name, Student::gradeAverage),
excludeId()
)
collection.find().projection(combinedProj)

You can use helpers from the Sorts builders class to sort on your data class properties. To learn more about this class, see the Sorts Builders guide.

The following code shows how to use Sorts extension methods to create different sorts on the Student data class:

import com.mongodb.client.model.Sorts.orderBy
import com.mongodb.kotlin.client.model.Sorts
val sort = orderBy(
Sorts.descending(Student::gradeAverage),
Sorts.ascending(Student::name)
)
collection.find().sort(sort)

You can use helpers from the Updates builders class to perform updates by using your data class properties. To learn more about this class, see the Updates Builders guide.

The following code shows how to use Sorts extension methods to create different sorts on the Student data class:

import com.mongodb.kotlin.client.model.Filters.gte
import com.mongodb.kotlin.client.model.Updates.addToSet
import com.mongodb.kotlin.client.model.Updates.combine
import com.mongodb.kotlin.client.model.Updates.max
val filter = Student::gradeAverage gte 85.0
val update = combine(
addToSet(Student::teachers, "Soto"),
Student::gradeAverage.max(90.0)
)
collection.updateMany(filter, update)

You can use helpers from the Aggregates and Accumulators builders classes to perform aggregations by using you data class properties. To learn more about these classes, see the Aggregates Builders guide.

The following code shows how to use Accumulators extension methods and Aggregates helper methods to perform an aggregation on the Student data class:

import com.mongodb.client.model.Aggregates.group
import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.sort
import com.mongodb.kotlin.client.model.Accumulators.avg
// Data class to store aggregation result
data class Summary ( val average: Double )
val pipeline = listOf(
// Sorts grades from high to low
sort(Sorts.descending(Student::gradeAverage)),
// Selects the top 3 students
limit(3),
// Calculates the average of their grades and stores value in a Summary instance
group(null, avg(Summary::average, "\$${Student::gradeAverage.name}"))
)
val result = collection.aggregate<Summary>(pipeline)
  • Kotlin driver Extensions

Back

Update