decode
Decodes this array into an instance of the Kotlin type T.
T should be a type that contains elements, such as List<Int> or Set<User>.
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) // 13Throws
If the value cannot be decoded as an instance of 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) // 30Throws
If the value cannot be decoded as an instance of 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