Scala Mongo driver - Convert a Document to a case class

1,355 views
Skip to first unread message

Sofiane Cherchalli

unread,
Mar 29, 2016, 2:51:45 PM3/29/16
to mongodb-user
Hi,

I want to convert a org.mongodb.scala.bson.collection.immutable.Document to the following case class:

case class Entry(id: String, values: Seq[SubEntry])
case class SubEntry(code: String, value:)

I am unable to figure out how to convert the sequence to the case class.

Here is my attempt with implicit class:

object Helpers {
  implicit class DocumentAs(doc: Document) {
    def asSubEntry: Option[SubEntry] = {
      for {
        x <- doc.get[BsonString]("code") map (_.asString().getValue)
        y <- doc.get[BsonInt64]("value") map (_.asInt64().getValue)
      } yield SubEntry(x, y)
    }

    def asEntry: Option[Entry] = {
      for {
        x <- doc.get[BsonString]("id") map (_.asString().getValue)
        y <- doc.get[BsonArray]("values") map (_.asArray ???)
      } yield Entry(x, y)
    }
  }
}

def findEntry(id: String): Future[Option[Entry]] = {
  val col: MongoCollection[Document] = mongo.db.getCollection("mycol")
  for {
    doc <- col.find(equal("id", id)).head()
    entry <- doc.asEntry
  } yield Some(entry)
}

Any hints on how to convert the BsonArray to a Seq[SubEntry] ?

Thanks

Sofiane Cherchalli

unread,
Mar 31, 2016, 2:40:49 AM3/31/16
to mongodb-user
Any taker?

Ross Lawley

unread,
Apr 19, 2016, 4:49:06 AM4/19/16
to mongodb-user
Hi Sofiane,

BsonArray has a getValues() method which will return a Java list of BsonValues. So you can do:

  import scala.collection.JavaConverters._
  def asEntry: Option[Entry] = {
      for {
        x <- doc.get[BsonString]("id") map (_.asString().getValue)
        y <- doc.get[BsonArray]("values").map(_.getValues.asScala.flatMap(bv => asSubEntry(bv.asDocument))).toSeq
      } yield Entry(x, y)
    }

All the best,

Ross
Reply all
Reply to author
Forward
0 new messages