Skip to content

opensavvy.ktmongo.dsl.path

Syntax to refer to specific fields in MongoDB documents.

When creating a query, we need to refer to specific fields in a MongoDB document, which may be in a nested document or in an array. Traditionally, this is done with the string representation of the path, but that leads to brittle code that is hard to navigate and refactor. Instead, KtMongo provides a DSL to refer to fields with type-safety:

User::_id                          // _id
User::profile / Profile::name      // profile.name
User::friends[1] / Friend::name    // friends.1.name

The operators are implemented in the interface FieldDsl which is already brought into scope by all KtMongo methods, and return instances of Field, the type-safe representation of a MongoDB path.

Operators

Types

Field

interface Field<in Root, out Type>

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

FieldDsl

interface FieldDsl

Operators to construct MongoDB field references from Kotlin code.

Path

@LowLevelApi



data class Path(val segment: PathSegment, val parent: Path?)

Low-level, type-unsafe pointer to a specific field in a document.

PathSegment

@LowLevelApi



sealed class PathSegment

Single segment in a Path.

PropertyNameStrategy

Allows configuring how the DSL generates MongoDB paths from KProperty1 instances.

Functions

at

infix inline fun <T> Bson.at(field: Field<*, T>): T

Finds the first value that matches path in a given BSON document.

select

inline fun <T> Bson.select(field: Field<*, T>): Sequence<T>

Finds all values that match field in a given BSON document.

selectFirst

inline fun <T> Bson.selectFirst(field: Field<*, T>): T

Finds the first value that matches field in a given BSON document.