Casbah Scala MongoDB driver - getting data from a DBObject Casbah Scala MongoDB driver - getting data from a DBObject mongodb mongodb

Casbah Scala MongoDB driver - getting data from a DBObject


You can use MongoDBObject's as method to get value and cast it in one call:

val coll = MongoConnection()(dbName)(collName)val query = MongoDBObject("title" -> "some value")val obj = coll findOne queryval someStr = obj.as[String]("title")val someInt = obj.as[Int]("count")// and so on..

Note that as throws an exception if given key cannot be found. You may use getAs which gives you Option[A]:

obj.getAs[String]("title") match {    case Some(someStr) => ...    case None => ...}

Extracting lists is a bit more complicated:

val myListOfInts =  (List() ++ obj("nums").asInstanceOf[BasicDBList]) map { _.asInstanceOf[Int] }

I wrote a helper, which makes using casbah more consice, may be it will be helpful, so I attach it:

package utilsimport com.mongodb.casbah.Imports._class DBObjectHelper(underlying: DBObject) {  def asString(key: String) = underlying.as[String](key)  def asDouble(key: String) = underlying.as[Double](key)  def asInt(key: String) = underlying.as[Int](key)  def asList[A](key: String) =    (List() ++ underlying(key).asInstanceOf[BasicDBList]) map { _.asInstanceOf[A] }  def asDoubleList(key: String) = asList[Double](key)}object DBObjectHelper {  implicit def toDBObjectHelper(obj: DBObject) = new DBObjectHelper(obj)}

You can use helper like this:

val someStr = obj asString "title"val someInt = obj asInt "count"val myDoubleList = obj asDoubleList "coords"

I hope it will help you.


If you're not afraid of using additional dependencies, use Salat. With Salat it is really simple to cast case classes to database object and back.

serialization

val dbo = grater[Company].asDBObject(company)

deserialization

val company_* = grater[Company].asObject(dbo)