Skip to content

Kotlin BSON • Multiplatform abstraction for different BSON implementationsopensavvy.ktmongo.bsonBsonPath

BsonPath

sealed interface BsonPath

Access specific fields in arbitrary BSON documents using a JSONPath-like API.

To access fields of a BSON document, use select or at.

Why BSON paths?

Most of the time, users want to deserialize documents, which they can do with opensavvy.ktmongo.bson.read.

However, sometimes, we receive large BSON payloads but only care about a few fields (for example, an explain plan). Writing an entire DTO for such payloads is time-consuming and complex.

Deserializing only a few specific fields can be much faster than deserializing the entire payload, as BSON is designed to allow skipping unwanted fields.

We may also face a payload that is too dynamic to easily deserialize, or with so much nesting that accessing fields becomes boilerplate.

In these situations, it may be easier (and often, more performant) to only deserialize a few specific fields, which is what BsonPath is useful for.

Syntax

BsonPath["foo"]    // Refer to the field 'foo': $.foo
BsonPath[0]        // Refer to the item at index 0: $[0]
BsonPath["foo"][0] // Refer to the item at index 0 in the array named 'foo': $.foo[0]

Accessing data

Find the first value for a given BSON path using at:

val document: Bson = 

val name = document at BsonPath["profile"]["name"]

Find all values for a given BSON path using select:

val document: Bson = 

document.select(BsonPath["profile"])
    .forEach { println("Found $it") }

Inheritors

Types

PathOrSelector

Marker interface for types that implement both BsonPath and Selector.

Root

object Root : BsonPath

The root of a BsonPath expression.

Selector

sealed interface Selector

Represents a unique selector in a multi-selector segment.

Properties

all

open val all: BsonPath

Points to all children of a document.

parent

abstract val parent: BsonPath?

The parent path of this path: the same path without the last segment.

Functions

any

open fun any(vararg selectors: BsonPath.Selector): BsonPath

Allows specifying multiple selectors.

findIn

@LowLevelApi
abstract fun findIn(reader: BsonValueReader): Sequence<BsonValueReader>

Applies the filters described by this path on the reader.

get

open operator fun get(index: Int): BsonPath

Points to the element at index in a BsonArray.

open operator fun get(field: String): BsonPath

Points to a field in a Bson document.

reversed

open fun reversed(): BsonPath

Iterates a BsonArray in the reversed order, starting from the end.

sliced

open fun sliced(range: IntProgression): BsonPath

Points to the elements of a BsonArray at the indices selected by range.

open fun sliced(start: Int? = null, end: Int? = null, step: Int = 1): BsonPath

Points to the elements of a BsonArray at the indices selected by start and end, with an optional step.