The Mongo Scala driver comes with helpers to transform basic Scala types to BsonValues, and that includes a BsonTransformer for java.util.Date. However, if you are using Joda DateTime, you need to provide a custom transformer to the Scala driver to marshal Joda DateTime to BsonValue and vice versa, and using the code below helps you achieve that.

class JodaCodec extends Codec[DateTime] {

  override def decode(bsonReader: BsonReader, decoderContext: DecoderContext): DateTime = new DateTime(bsonReader.readDateTime())

  override def encode(bsonWriter: BsonWriter, t: DateTime, encoderContext: EncoderContext): Unit = bsonWriter.writeDateTime(t.getMillis)

  override def getEncoderClass: Class[DateTime] = classOf[DateTime]
}

Let’s say we have the following case class that has a created field with a Joda DateTime as its type.

case class Record(id: String, created: DateTime)

To enable the marshalling of the above case class to a bson Document and vice versa, we will need to bind the above JodaCodec to the Scala driver’s codec registry as below.

val codecRegistry = fromRegistries(
  fromProviders(classOf[Record]),
  CodecRegistries.fromCodecs(new JodaCodec),
  DEFAULT_CODEC_REGISTRY
)

And that should take care of retrieving and saving documents with Joda DateTime fields.