How to force Kotlin Instant to be serialized as BsonDateTime instead of BsonString

Hello,

I am working with the Kotlin coroutines driver and bson-kotlinx library. I want to have the Instant datatype (from kotlinx-datetime) serialized as mongo dates instead of strings.

This is what I am trying

class InstantStatusCodec : Codec<Instant> {

    override fun encode(writer: BsonWriter, value: Instant, encoderContext: EncoderContext) =
        writer.writeDateTime(value.toEpochMilliseconds())

    override fun decode(reader: BsonReader, decoderContext: DecoderContext): Instant =
        Instant.fromEpochMilliseconds(reader.readDateTime())

    override fun getEncoderClass(): Class<Instant> = Instant::class.java
}

private val codecRegistry = CodecRegistries.fromRegistries(
    CodecRegistries.fromCodecs(InstantStatusCodec()),
    MongoClientSettings.getDefaultCodecRegistry()
)


mongoClient
      .getDatabase(database)
      .getCollection(collectionName, resourceType)
      .withCodecRegistry(codecRegistry)

But at the end I am still seeing Strings in the database for Instant fields.
Can anyone give me a hint?

Thanks!

Take a look this this and this

object InstantAsBsonDateTime : KSerializer<Instant> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("InstantAsBsonDateTime", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Instant) {
        when (encoder) {
            is BsonEncoder -> encoder.encodeBsonValue(BsonDateTime(value.toEpochMilliseconds()))
            else -> throw SerializationException("Instant is not supported by ${encoder::class}")
        }
    }

    override fun deserialize(decoder: Decoder): Instant {
        return when (decoder) {
            is BsonDecoder -> Instant.fromEpochMilliseconds(decoder.decodeBsonValue().asDateTime().value)
            else -> throw SerializationException("Instant is not supported by ${decoder::class}")
        }
    }
}