当前位置: 首页 > 工具软件 > Casbah > 使用案例 >

scala连接mongodb_Casbah Scala MongoDB驱动程序 – 从DBObject获取数据

笪栋
2023-12-01

您可以使用MongoDBObject作为方法来获取值并将其转换为一次调用:

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..

请注意,如果找不到给定的密钥,则抛出异常.您可以使用getAs为您提供选项[A]:

obj.getAs[String]("title") match {

case Some(someStr) => ...

case None => ...

}

提取列表有点复杂:

val myListOfInts =

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

我写了一个帮手,这使得使用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"

我希望它会对你有所帮助.

 类似资料: