mongodbscalamongodb-scala

MongoDB Scala Driver counterpart to Javascript Object


I am trying to create a document with the counterpart to a Javascript Object Map[String, Any]. When I try to insert a new Document I'll get this Exception:

org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.lang.Object.

This is my test document description:

import org.mongodb.scala.bson.ObjectId

object ExampleCollection {
  def apply(test: Map[String, Any]): ExampleCollection = new ExampleCollection(new ObjectId(), test)
}

case class ExampleCollection(_id: ObjectId, test: Map[String, Any])

This is the Codec Registry:

val codecRegistry = fromRegistries(fromProviders(classOf[ExampleCollection]), DEFAULT_CODEC_REGISTRY)

I have written a small Application and pushed it on github.

For now, my workaround would be to serialize the Map[String, Any] and save it as String.

So, my question would be, what do I have to do to use Map[String, Any] as a type for my dynamic object in mongodb? Or can I do something else to get it working?


Solution

  • You cannot pass just Any to mongo, as soon as it does not know what it is and how to serialize/deserialize it. If it is json, you can try to convert it to BSONDocument instead of Map with unknown format.

    For example, see here case for converting play-json.