Skip to content

BsonFactory

interface BsonFactory

Entrypoint for creating Bson and BsonArray instances.

Instances of this interface are platform-specific and are used to create BSON documents. Each instance may allow parameterization of some behaviors.

Functions

buildArray

@LowLevelApi



abstract fun buildArray(block: BsonValueWriter.() -> Unit): BsonArray

Instantiates a new BSON array.

Example

To create the following BSON array:

[
    12,
    null,
    {
        "name": "Barry"
    }
]

use the code:

buildArray {
    writeInt32(12)
    writeNull()
    writeDocument {
        writeString("name", "Barry")
    }
}
@LowLevelApi



open fun buildArray(instance: BsonValueWriteable): BsonArray

Instantiates a new BSON array representing the provided instance.

buildDocument

@LowLevelApi



abstract fun buildDocument(block: BsonFieldWriter.() -> Unit): Bson

Instantiates a new BSON document.

Example

To create the following BSON document:

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

use the code:

buildDocument {
    writeString("name", "Alice")
    writeBoolean("isAlive", true)
    writeArray("children") {
        writeDocument {
            writeString("name", "Alice")
        }
        writeDocument {
            writeString("name", "Charles")
        }
    }
}
@LowLevelApi



open fun buildDocument(instance: BsonFieldWriteable): Bson

Instantiates a new BSON document representing the provided instance.

@LowLevelApi



abstract fun <T : Any> buildDocument(
    obj: T, 
    type: KType, 
    klass: KClass<T>
): Bson

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

Prefer using BsonContext.write.

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.

readArray

@LowLevelApi



abstract fun readArray(bytes: ByteArray): BsonArray

Instantiates a new BSON array by reading its bytes representation.

The reverse operation is available as BsonArray.toByteArray.

readDocument

@LowLevelApi



abstract fun readDocument(bytes: ByteArray): Bson

Instantiates a new BSON document by reading its bytes representation.

The reverse operation is available as Bson.toByteArray.

write

inline fun <T : Any> BsonFactory.write(obj: T): Bson

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

  • read: The inverse operation.