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

Root

object Root : BsonPath

The root of a BsonPath expression.

Functions

findIn

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

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.