您可以使用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
,让你Option[A]
:
obj.getAs[String]("title") match {
case Some(someStr) => ...
case None => ...
}
提取列表是一个比较复杂一点:
val myListOfInts =
(List() ++ obj("nums").asInstanceOf[BasicDBList]) map { _.asInstanceOf[Int] }
我写了一个帮手,这使得使用卡斯巴更consice,可能会有帮助,所以我将其附加:
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"
我希望它能帮助你。
哇,涵盖了这个话题非常好!谢谢,这显然现在被选为最佳答案。 – noncom
当调用val obj = coll.findOne(query)时,我得到'value getAs不是Option [coll.T]的成员'; val str = obj.getAs [String](“myValue”)'。 –
该示例不起作用,'findOne'返回'Option'类型。 – andyczerwonka