The following code shows a bug deserializing data into a MongoCollection
@Serializable sealed interface Pet { val name: String } @Serializable data class Dog( @Contextual @SerialName("_id") val id: ObjectId, override val name: String, val favoriteToy: String, ) : Pet @Serializable data class Cat( @Contextual @SerialName("_id") val id: ObjectId, override val name: String, val favoritePlace: String, ) : Pet suspend fun main() { val winston = Dog(ObjectId(), "Winston", "Ball") val collection = MongoClient.create().getDatabase("test").getCollection<Pet>("Pet") collection.insertOne(winston) collection.withDocumentClass<Document>().find().first().also { println(it) } collection.withDocumentClass<Dog>().find().first().also { println(it) } collection.withDocumentClass<Pet>().find().first().also { println(it) } // FAILS with a codec error: Stack trace: Exception in thread "main" org.bson.BsonInvalidOperationException: Reading field '_id' failed expected STRING type but found: OBJECT_ID. at org.bson.codecs.kotlinx.DefaultBsonDecoder.decodeString(BsonDecoder.kt:302) at kotlinx.serialization.encoding.AbstractDecoder.decodeStringElement(AbstractDecoder.kt:58) at kotlinx.serialization.internal.AbstractPolymorphicSerializer.deserialize(AbstractPolymorphicSerializer.kt:52) at org.bson.codecs.kotlinx.KotlinSerializerCodec.decode(KotlinSerializerCodec.kt:182) }