Skip to content

Field

interface Field<in Root, out Type>

High-level, typesafe pointer to a specific field in a document.

This type may refer to fields nested in children documents or arrays. Instances are generally used to refer to a MongoDB field we want to read or update, when writing requests.

Type safety

This type is responsible for ensuring type safety:

class User(
    val _id: ObjectId,
    val profile: Profile,
    val friends: List<Friend>,
)

class Profile(
    val name: String,
)

class Friend(
    val name: String,
    val age: Int,
)

// Refer to the user's id
println(User::_id.field)
// _id

// Refer to the user's name
println(User::profile / Profile::name)
// profile.name

// Refer to the name of the second friend
println(User::friends[1] / Friend::name)
// friends.1.name

An instance of FieldDsl is required in scope to call these methods. All KtMongo commands automatically bring an instance of FieldDsl into scope.

For example, when writing a filter, methods from this interface are automatically available:

collection.find {
    User::profile / Profile::name eq "Thibault Lognaise"
}

To bypass type-safety, and refer to arbitrary fields without declaring them first, see unsafe.

Parameters

  • Root: The type of the document in which this field is in.

  • Type: The type of the value stored by this field.

Types

Companion

object Companion

Properties

path

@LowLevelApi



abstract val path: Path

Low-level representation of this field's path.

Functions

toBsonPath

@LowLevelApi



fun Path.toBsonPath(): BsonPath

Converts this MongoDB Path to a BsonPath.

BsonPath is an implementation of RFC9535 JSONPath. See its documentation for more information.

fun Field<*, *>.toBsonPath(): BsonPath

Converts this MongoDB Field to a BsonPath.

BsonPath is an implementation of RFC9535 JSONPath. See its documentation for more information.

BsonPath can be useful to access elements from an arbitrary BSON document, for example, after a projection.

Example
data class User(
    val _id: ObjectId,
    val profile: Profile,
)

data class Profile(
    val name: String,
)

val fieldName = (User::profile / Profile::name).toBsonPath()

val bson: Bson = 
val name = bson at fieldName

See also

  • select: Select multiple values.

  • selectFirst: Select the first value.

  • at: Select the first value, as an infix operator.