Skip to content

MongoDB driver for Kotlin (synchronous, with Java helpers)opensavvy.ktmongo.syncJavaField

JavaField

class JavaField<Root, Type> : Field<Root, Type> 

Type-safe representation of a dotted MongoDB field path from Java method references.

This class is used to type-safely refer to fields from a DTO. For example, if we have the DTO:

public record Invoice(
    @BsonId ObjectId id,
    Customer customer
) {

    public record Customer(
        String name,
        String address
    ) {}
}

We can refer to the different fields as:

  • "_id": JavaField.of(Invoice::id)

  • "customer": JavaField.of(Invoice::customer)

  • "customer.name": JavaField.of(Invoice::customer).child(Customer::name)

  • "customer.address": JavaField.of(Invoice::customer).child(Customer::address)

Because the generated reference is type-safe, you don't risk typos, and you can navigate from a DTO to all its usages in all requests using your usual IDE tooling.

Important note. If you're using KtMongo in a mixed Java-Kotlin project, note that this class has a slightly different mapping algorithm than the Kotlin Field implementations, because Kotlin has field references but Java doesn't, and Kotlin allows the name _id but Java doesn't. In Kotlin code, KtMongo always uses the Kotlin field name as-is, whereas this class will use _id if the field is annotated with @BsonId, remove the "get" prefix of a getter, etc. For the exact mapping algorithm, see the implementation.

See also

Types

Companion

object Companion

Properties

path

open override val path: Path

Functions

child

fun <T> child(accessor: SerializableLambdas.SerializableFunction1<Type, T>): JavaField<Root, T>

Refers to a specific field that is a child of the current field.

div

open operator fun <Child> div(child: KProperty1<in Type & Any, Child>): Field<Root, Child>
open operator fun <Child> div(child: Field<Type, Child>): Field<Root, Child>

unsafe

open fun <Child> unsafe(child: String): Field<Root, Child>