Skip to content

BsonFactory

class BsonFactory(serializersModule: SerializersModule = EmptySerializersModule()) : BsonFactory

Entrypoint for creating BsonDocument and BsonArray instances.

This interface is part of the BSON trinity:

Serialization

This interface encapsulates methods to serialize and serialize BSON documents with KotlinX.Serialization.

Usage

To create the following BSON document:

{
    "name": "Bob",
    "isAlive": true,
    "children": [
        {
            "name": "Alice"
        },
        {
            "name": "Charles"
        }
    ]
}

use the code:

val document = factory.buildDocument {
    writeString("name", "Alice")
    writeBoolean("isAlive", true)
    writeArray("children") {
        writeDocument {
            writeString("name", "Alice")
        }
        writeDocument {
            writeString("name", "Charles")
        }
    }
}

The value can then be read into Kotlin types:

@Serializable
data class User(
    val name: String,
    val isAlive: Boolean,
    val children: List<Child>,
)

@Serializable
data class Child(
    val name: String,
)

val user = document.decode<User>()

println(user.children[0].name)  // Alice

Constructors

BsonFactory

constructor(serializersModule: SerializersModule = EmptySerializersModule())

Properties

serializersModule

The SerializersModule used by this factory when encoding or decoding BSON types.

To customize this module, see the constructor of opensavvy.ktmongo.bson.multiplatform.BsonFactory.

Functions

buildArray

@LowLevelApi
open override fun buildArray(block: BsonValueWriter.() -> Unit): BsonArray

buildDocument

@LowLevelApi
open override fun buildDocument(block: BsonFieldWriter.() -> Unit): BsonDocument

encode

@ExperimentalSerializationApi
@LowLevelApi
open override fun <T : Any> encode(obj: T, type: KType): BsonDocument

encode

Writes an arbitrary Kotlin obj into a top-level BSON document.

A top-level BSON document cannot be null, cannot be a primitive, and cannot be a collection. If obj is not representable as a document, an exception is thrown.

See also

readArray

@LowLevelApi
open override fun readArray(bytes: ByteArray): BsonArray

readDocument

@LowLevelApi
open override fun readDocument(bytes: ByteArray): BsonDocument