You can use the MongoDBObject as method to get the value and make it one call:
val coll = MongoConnection()(dbName)(collName) val query = MongoDBObject("title" -> "some value") val obj = coll findOne query val someStr = obj.as[String]("title") val someInt = obj.as[Int]("count") // and so on..
Note that as throws an exception if the specified key is not found. You can use getAs , which gives you Option[A] :
obj.getAs[String]("title") match { case Some(someStr) => ... case None => ... }
Retrieving lists is a bit more complicated:
val myListOfInts = (List() ++ obj("nums").asInstanceOf[BasicDBList]) map { _.asInstanceOf[Int] }
I wrote an assistant that makes using casbah more demise, maybe it will be useful, so I attach it:
package utils import 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 the helper helper:
val someStr = obj asString "title" val someInt = obj asInt "count" val myDoubleList = obj asDoubleList "coords"
Hope this helps you.
lambdas
source share