Skip to content

BsonValue

An arbitrary BSON value.

The BSON specification only allows root documents, so it is not possible to instantiate this interface directly with a complex structure. This interface is used to decode the fields of a BsonDocument or the items of a BsonArray.

To instantiate a BsonDocument or BsonArray, see BsonFactory.

This interface is part of the BSON trinity:

Usage

If this BSON value is the serialized form of a Kotlin DTO, see decode.

This interface provides methods for decoding the different BSON native types, like decodeInt32, decodeObjectId and decodeInstant.

Some BSON types cannot be represented by a single Kotlin type, so multiple methods are provided to decode their components. For example: decodeRegularExpressionPattern and decodeRegularExpressionOptions.

Equality

Different implementations of this interface are considered equal if they represent the same value with the same type. That is, both values would result in the exact same BSON sent over the wire.

The methods BsonValue.Companion.equals and BsonValue.Companion.hashCode are provided as default implementations.

Types

Companion

object Companion

Properties

factory

abstract val factory: BsonFactory

The instance of BsonFactory that created this instance.

BsonFactory contains the serialization configuration that apply to this value.

type

abstract val type: BsonType

The native BSON type of this value.

Functions

decode

@LowLevelApi
abstract fun <T> decode(type: KType): T

Decodes this value into an instance of the Kotlin type T.

Serialization configuration

This method uses the serialization methods configured in the BsonFactory that created this instance.

For example, if you use the official Java or Kotlin MongoDB drivers, this method will use your configured CodecRegistry.

Example

data class User(
    val name: String,
    val age: Int,
)

val factory: BsonFactory = 

val bson = factory.buildDocument {
    writeDocument("personalInfo") {
        writeString("name", "Bob")
        writeInt32("age", 30)
    }
}

val user = bson["personalInfo"]!!.decode<User>()

println(user.name)  // Bob
println(user.age)   // 30

Overloads

Prefer using the parameter-less overload.

If type doesn't match T, the behavior is unspecified.

Throws

BsonDecodingException

If the value cannot be decoded as an instance of T.

decode

inline fun <T> BsonArray.decode(): T

Decodes this array into an instance of the Kotlin type T.

<strong>T</strong> should be a type that contains elements, such as <strong>List<Int></strong> or <strong>Set<User></strong>.

To decode this array as a List of elements, see decodeElements instead.

Serialization configuration

This method uses the serialization methods configured in the BsonFactory that created this instance.

For example, if you use the official Java or Kotlin MongoDB drivers, this method will use your configured CodecRegistry.

Example

data class User(
    val name: String,
    val age: Int?,
)

val factory: BsonFactory = 

val bson = factory.buildDocument {
    writeArray("users") {
        writeDocument {
            writeString("name", "Alice")
            writeInt32("age", 13)
        }

        writeDocument {
            writeString("name", "Bob")
            writeInt32("age", 52)
        }
    }
}

val users = bson["users"]?.decode<List<User>>()

println(users[0].name) // Alice
println(users[1].age)  // 13

Throws

BsonDecodingException

If the value cannot be decoded as an instance of T.

inline fun <T> BsonDocument.decode(): T

Decodes this document into an instance of the Kotlin type T.

Serialization configuration

This method uses the serialization methods configured in the BsonFactory that created this instance.

For example, if you use the official Java or Kotlin MongoDB drivers, this method will use your configured CodecRegistry.

Example

data class User(
    val _id: ObjectId,
    val profile: Profile,
)

data class Profile(
    val name: String,
    val age: Int?,
)

val factory: BsonFactory = 

val bson = factory.buildDocument {
    writeObjectId("_id", ObjectId("69c93e17b96e83b72d11b734"))
    writeDocument("profile") {
        writeString("name", "Bob")
        writeInt32("age", 30)
    }
}

val user = bson.decode<User>()

println(user._id)          // ObjectId(69c93e17b96e83b72d11b734)
println(user.profile.name) // Bob
println(user.profile.age)  // 30

Throws

BsonDecodingException

If the value cannot be decoded as an instance of T.

inline fun <T> BsonValue.decode(): T

Decodes this value into an instance of the Kotlin type T.

Serialization configuration

This method uses the serialization methods configured in the BsonFactory that created this instance.

For example, if you use the official Java or Kotlin MongoDB drivers, this method will use your configured CodecRegistry.

Example

data class User(
    val name: String,
    val age: Int,
)

val factory: BsonFactory = 

val bson = factory.buildDocument {
    writeDocument("personalInfo") {
        writeString("name", "Bob")
        writeInt32("age", 30)
    }
}

val user = bson["personalInfo"]!!.decode<User>()

println(user.name)  // Bob
println(user.age)   // 30

decodeArray

abstract fun decodeArray(): BsonArray

Decodes this value as a nested BsonArray.

Throws

BsonDecodingException

If the value is not a BsonType.Array.

decodeBinaryData

abstract fun decodeBinaryData(): ByteArray

Decodes a binary blob.

The BsonType.BinaryData type stores an additional byte to know what kind of data is stored. To decode that type, see decodeBinaryDataType.

The binary data types 0..127 are reserved. The data types 128..255 are available for custom use.

The binary data type 0 is a generic subtype that can be used for any usage.

Note that the KtMongo library provides utilities for some specific binary types:

External resources

Throws

BsonDecodingException

If the value is not a BsonType.BinaryData.

decodeBinaryDataType

abstract fun decodeBinaryDataType(): UByte

Decodes the type of a binary blob.

The BsonType.BinaryData type stores an additional byte to know what kind of data is stored. To decode the data itself, see decodeBinaryData.

The binary data types 0..127 are reserved. The data types 128..255 are available for custom use.

The binary data type 0 is a generic subtype that can be used for any usage.

Note that the KtMongo library provides utilities for some specific binary types:

External resources

Throws

BsonDecodingException

If the value is not a BsonType.BinaryData.

decodeBoolean

abstract fun decodeBoolean(): Boolean

Decodes this value as a Boolean.

Throws

BsonDecodingException

If the value is not a BsonType.Boolean.

decodeDateTime

abstract fun decodeDateTime(): Long

Decodes this value as a UTC timestamp in milliseconds since the Unix epoch.

See also

Throws

BsonDecodingException

If the value is not a BsonType.Datetime.

decodeDBPointerId

abstract fun decodeDBPointerId(): ObjectId

Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Decodes this value as the ID of a database pointer.

Database pointers are deprecated values that are composed of the name of a collection, and the identifier of one of its documents.

To read the namespace, see decodeDBPointerNamespace.

Throws

BsonDecodingException

If the value is not a BsonType.DBPointer.

decodeDBPointerNamespace

Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Decodes this value as the namespace of a database pointer.

Database pointers are deprecated values that are composed of the name of a collection, and the identifier of one of its documents.

To read the identifier, see decodeDBPointerId.

Throws

BsonDecodingException

If the value is not a BsonType.DBPointer.

decodeDecimal128Bytes

Decodes this value as the bytes of a Decimal128.

Throws

BsonDecodingException

If the value is not a BsonType.Decimal128.

decodeDocument

abstract fun decodeDocument(): BsonDocument

Decodes this value as a nested BsonDocument.

Throws

BsonDecodingException

If the value is not a BsonType.Document.

decodeDouble

abstract fun decodeDouble(): Double

Decodes this value as Double.

Throws

BsonDecodingException

If the value is not a BsonType.Double.

decodeInstant

open fun decodeInstant(): Instant

Decodes this value as a Kotlin Instant.

Throws

BsonDecodingException

If the value is not a BsonType.Datetime.

decodeInt32

abstract fun decodeInt32(): Int

Decodes this value as Int.

Throws

BsonDecodingException

If the value is not a BsonType.Int32.

decodeInt64

abstract fun decodeInt64(): Long

Decodes this value as Long.

Throws

BsonDecodingException

If the value is not a BsonType.Int64.

decodeJavaScript

abstract fun decodeJavaScript(): String

Decodes this value as JavaScript code.

If this value has type BsonType.JavaScriptWithScope, see decodeJavaScriptScope.

Throws

BsonDecodingException

If the value is not a BsonType.JavaScript or BsonType.JavaScriptWithScope.

decodeJavaScriptScope

Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Decodes this value as a document describing variables some JavaScript code has access to.

The accompanying JavaScript code is accessed with decodeJavaScript.

Throws

BsonDecodingException

If the value is not a BsonType.JavaScriptWithScope.

decodeMaxKey

abstract fun decodeMaxKey()

Decodes the special BSON value BsonType.MaxKey.

Throws

BsonDecodingException

If the value is not a BsonType.MaxKey.

decodeMinKey

abstract fun decodeMinKey()

Decodes the special BSON value BsonType.MinKey.

Throws

BsonDecodingException

If the value is not a BsonType.MinKey.

decodeNull

abstract fun decodeNull(): Nothing?

Decodes this value as a Kotlin null.

Note that we differentiate "the value is not present" with "the value as the BSON type null". This method only returns successfully in the presence of the BSON type null.

A BsonValue cannot represent an absent value, so there is no "check if present" method. Instead, BsonDocument.get and BsonArray.get return null (NOT a BsonValue that decodes to null) if the field is absent.

Throws

BsonDecodingException

If the value is not a BsonType.Null.

decodeObjectId

open fun decodeObjectId(): ObjectId

Decodes this value as a ObjectId.

Throws

BsonDecodingException

If the value is not a BsonType.ObjectId.

decodeObjectIdBytes

Decodes this value as the bytes of an ObjectId.

Prefer using decodeObjectId, which offers utilities to access its different components, like ObjectId.timestamp.

Throws

BsonDecodingException

If the value is not a BsonType.ObjectId.

decodeRegularExpressionOptions

Decodes this value as the options of a regular expression.

A BSON regular expression is composed of a pattern and options. To decode the pattern, see decodeRegularExpressionPattern.

Throws

BsonDecodingException

If the value is not a BsonType.RegExp.

decodeRegularExpressionPattern

Decodes this value as the pattern of a regular expression.

A BSON regular expression is composed of a pattern and options. To decode the options, see decodeRegularExpressionOptions.

Throws

BsonDecodingException

If the value is not a BsonType.RegExp.

decodeString

abstract fun decodeString(): String

Decodes this value as a string.

Throws

BsonDecodingException

If the value is not a BsonType.String.

decodeSymbol

abstract fun decodeSymbol(): String

Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Decodes this value as a symbol.

Throws

BsonDecodingException

If the value is not a BsonType.Symbol.

decodeTimestamp

abstract fun decodeTimestamp(): Timestamp

Decodes this value as a Timestamp.

Timestamp is a special MongoDB type with a precision of one second, which is mainly used in the oplog.

For everyday use cases, the Kotlin type Instant (see decodeInstant) is a better alternative, with millisecond precision.

Throws

BsonDecodingException

If the value is not a BsonType.Timestamp.

decodeUndefined

abstract fun decodeUndefined()

Deprecated

This functionality is deprecated in the BSON specification. See https://bsonspec.org/spec.html

Decodes this value as an undefined value.

Throws

BsonDecodingException

If the value is not a BsonType.Undefined.

decodeVector

open fun decodeVector(): Vector

Decodes a binary Vector.

Throws

BsonDecodingException

If the value is not a BsonType.BinaryData with subtype 0x09.

diff

infix fun BsonDocument.diff(other: BsonDocument): String?

Analyzes the difference between two BSON documents.

This function is particularly useful in tests. Since BSON documents can be large, it may be difficult to find what the difference between two documents is.

This function generates human-readable output to find the differences.

Example

val a = factory.buildDocument {
    writeString("a", "foo")
    writeDocument("b") {
        writeString("name", "Bob")
        writeInt32("age", 18)
    }
}

val b = factory.buildDocument {
    writeString("a", "foo")
    writeDocument("b") {
        writeString("name", "Alice")
        writeInt32("age", 19)
    }
}

println(a diff b)
✓ a: "foo"
✗ b:
     ✗ name: "Bob"
             "Alice"
     ✓ age: 18
            19

Return

If the two documents are equal, returns null. Otherwise, generates a human-readable diff.

infix fun BsonArray.diff(other: BsonArray): String?

Analyzes the difference between two BSON arrays.

This function is particularly useful in tests. Since BSON arrays can be large, it may be difficult to find what the difference between two documents is.

This function generates human-readable output to find the differences.

Example

val a = factory.buildArray {
    writeString("foo")
    writeDocument {
        writeString("name", "Bob")
        writeInt32("age", 18)
    }
}

val b = factory.buildArray {
    writeString("foo")
    writeDocument {
        writeString("name", "Alice")
        writeInt32("age", 19)
    }
}

println(a diff b)
✓ 0: "foo"
✗ 1:
     ✗ name: "Bob"
             "Alice"
     ✓ age: 18
            19

Return

If the two arrays are equal, returns null. Otherwise, generates a human-readable diff.

infix fun BsonValue.diff(other: BsonValue): String?

Analyzes the difference between two BSON values.

This function is particularly useful in tests. Since BSON documents can be large, it may be difficult to find what the difference between two documents is.

This function generates human-readable output to find the differences.

Return

If the two documents are equal, returns null. Otherwise, generates a human-readable diff.

takeIfPresent

open fun takeIfPresent(): BsonValue?

Returns this value, unless it is undefined or null, in which case returns null.

See also