Internally, MongoDB stores all of its data in a Bson (Binary JSON) format, which is a close cousin of a traditional Json that we all got used to. Similarities between these two formats allow us to derive MongoDB codecs with the help of tools that are normally used for doing transformations of case classes into a Json. One of such tools is Circe.

To enable Circe support, a dependency has to be added in the build.sbt:

libraryDependencies += "io.github.kirill5k" %% "mongo4cats-circe" % "<version>"

Once the dependency is in, automatic derivation of MongoDB codecs can be enabled by including the following import:

import mongo4cats.circe._

Which, when included, implicitly builds an instance of MongoCodecProvider[T], assuming there are instances of Encoder[T] and Decoder[T] available in the implicit scope:

import mongo4cats.bson.ObjectId
import mongo4cats.circe._
import mongo4cats.collection.MongoCollection

final case class MyClass(_id: ObjectId, field1: String, field2: Int)

val collection: IO[MongoCollection[IO, MyClass]] = database.getCollectionWithCodec[MyClass]("mycoll")