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


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) =

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

    override fun getEncoderClass(): Class<Instant> =

private val codecRegistry = CodecRegistries.fromRegistries(

      .getCollection(collectionName, resourceType)

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


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}")