您可以使用 MongoDBObject 的as
方法来获取值并将其转换为一次调用:
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..
请注意,as
如果找不到给定的键,则会引发异常。您可以使用getAs
which 为您提供Option[A]
:
obj.getAs[String]("title") match {
case Some(someStr) => ...
case None => ...
}
提取列表有点复杂:
val myListOfInts =
(List() ++ obj("nums").asInstanceOf[BasicDBList]) map { _.asInstanceOf[Int] }
我写了一个 helper,让使用 casbah 更加简洁,可能会有帮助,所以附上:
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)
}
您可以像这样使用助手:
val someStr = obj asString "title"
val someInt = obj asInt "count"
val myDoubleList = obj asDoubleList "coords"
我希望它会帮助你。