Skip to content

BsonDocument

A BSON document.

To create instances of this class, see BsonFactory.

This interface is part of the BSON trinity:

Usage

val bson: BsonDocument = 

for ((name, field) in bson) {
    println("Field: $name${field.type}")
}

The iteration order of a BSON document is preserved: fields appear in the same order as they are written in.

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 BsonDocument.Companion.equals and BsonDocument.Companion.hashCode are provided as default implementations.

Types

Companion

object Companion

Field

interface Field

A pair of a name and a value.

Properties

factory

abstract val factory: BsonFactory

The instance of BsonFactory that created this instance.

BsonFactory contains the serialization configuration that apply to this document.

fields

abstract val fields: Set<String>

Returns the set of fields in this document.

The iteration order of this set is the same as the iteration order as the document.

size

abstract val size: Int

The number of fields in this document.

Functions

asIterable

Creates an Iterable that wraps this document.

Each pair is the name of a field and its value.

The iteration order of a BSON document is preserved: fields appear in the same order as they are written in.

Requirements

asMap

abstract fun asMap(): Map<String, BsonValue>

Creates a Map view of this document.

Each entry associates a field and its value.

The iteration order of a BSON document is preserved: fields appear in the same order as they are written in.

Requirements

asSequence

Creates a Sequence of the fields in this document.

Each pair is the name of a field and its value.

The iteration order of a BSON document is preserved: fields appear in the same order as they are written in.

Requirements

The Sequence.toString output should follow the same rules as on BsonDocument itself.

asValue

abstract fun asValue(): BsonValue

Returns the BsonValue equivalent to this document.

The returned value has type BsonType.Document and its BsonValue.decodeDocument method returns this document.

at

infix inline fun <T> BsonDocument.at(path: BsonPath): T

Finds the first value that matches path in a given BSON document.

Example

val document: Bson = 

val bar: String = document at BsonPath["foo"]["bar"]

will return the value of the field foo.bar.

Depending on your situation, you can also use the equivalent function selectFirst:

val document: Bson = 

document.selectFirst<String>(BsonPath["foo"]["bar"])

See also

  • BsonPath: Learn more about BSON paths.

  • select: Select multiple values with a BSON path.

Throws

NoSuchElementException

If no element is found matching the path.

decode

@LowLevelApi
abstract fun <T> decode(type: KType): 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

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

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.

get

abstract operator fun get(field: String): BsonValue?

Returns the element with named field.

This method returns null if there is no element named field. Note that if there is an element named field, and it has the value null, then a BsonValue with type BsonType.Null is returned.

isEmpty

open fun isEmpty(): Boolean

Returns true if this document has no fields.

isNotEmpty

open fun isNotEmpty(): Boolean

Returns true if this document has at least one field.

iterator

abstract operator fun iterator(): Iterator<BsonDocument.Field>

Iterates over the fields in this document.

Each pair is the name of a field and its value.

The iteration order of a BSON document is preserved: fields appear in the same order as they are written in.

select

inline fun <T> BsonDocument.select(path: BsonPath): Sequence<T>

Finds all values that match path in a given BSON document.

Example

val document: Bson = 

document.select<String>(BsonPath["foo"]["bar"]).firstOrNull()

will return the value of the field foo.bar.

See also

  • BsonPath: Learn more about BSON paths.

  • selectFirst: If you're only interested about a single element. See also at.

inline fun <T> BsonDocument.select(@Language(value = "JSONPath") path: String): Sequence<T>

Finds all values that match path in a given BSON document.

To learn more about the syntax, see BsonPath.

Example

val document: Bson = 

document.select<String>("$.foo.bar")

will return a sequence of all values matching the path foo.bar.

See also

  • at: Select a single value.

selectFirst

inline fun <T> BsonDocument.selectFirst(path: BsonPath): T

Finds the first value that matches path in a given BSON document.

Example

val document: Bson = 

document.selectFirst<String>(BsonPath["foo"]["bar"])

will return the value of the field foo.bar.

Alternatives

Depending on your situation, you can also use the equivalent function at:

val document: Bson = 

val bar: String = document at BsonPath["foo"]["bar"]

See also

  • BsonPath: Learn more about BSON paths.

  • select: Select multiple values with a BSON path.

Throws

NoSuchElementException

If no element is found matching the path.

inline fun <T> BsonDocument.selectFirst(@Language(value = "JSONPath") path: String): T

Finds the first value that matches path in a given BSON document.

To learn more about the syntax, see BsonPath.

Example

val document: Bson = 

document.selectFirst<String>("$.foo.bar")

will return the value of the field foo.bar.

See also

  • BsonPath: Learn more about BSON paths.

  • select: Select multiple values with a BSON path.

  • at: Select a single value using infix notation.

toByteArray

abstract fun toByteArray(): ByteArray

Generates a ByteArray of the raw BSON representation of this value.

toString

abstract override fun toString(): String

JSON representation of this BsonDocument object, as a String.