writeSafe
Writes an arbitrary obj into a BSON document.
All nested values are escaped as necessary such that the result is a completely inert BSON document.
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 {
write("user") {
writeSafe("user", User(ObjectId("69c93e17b96e83b72d11b734"), Profile("Bob", 30)))
}
}
val user = bson.decode<User>()
println(user._id) // ObjectId(69c93e17b96e83b72d11b734)
println(user.profile.name) // Bob
println(user.profile.age) // 30Content copied to clipboard