0
我想從Casbah的MongoCollectionBase.find(...)返回的DBObject中提取某個鍵「orderItems」的值。我有解決方案,但我不滿意。我發現我的解決方案繁瑣。它將每個步驟中從DBObject.toMap返回的java.util.Map轉換並轉換爲Scala Map或其他集合。有什麼更好的辦法呢?由於使用Scala/Casbah從MongoDB DBObject提取值
val orders = provisioningDb("systems").find(MongoDBObject.empty, MongoDBObject("company.department.orders" -> 1))
import scala.collection.JavaConversions._
def findC(m : Map[String, Any]) : Iterable[Any] = {
val c = for ((k, v) <- m) yield (k, v) match {
case (k, v) if k equals "orderItems" => v
case (k, v : java.util.HashMap[String, Any]) => findC(toMap(v).asInstanceOf[Map[String, Any]]).head
case _ => Nil
}
c.filter(_.isInstanceOf[java.util.List[Any]])
}
def toMap[K, E](m: java.util.Map[K, E]): Map[K, E] = {
Map.empty ++ new MapWrapper[K, E](m)
}
val orderItems = for {
x <- orders
} yield x
for (y <- orderItems) {
println(findC(toMap(y.toMap).asInstanceOf[Map[String, Any]]))
}
去掉細節堅持MongoDB中的2行的樣本數據,
company : {department : {orders -> [{"id" : "543", "quantity" : 2}, {"id" : "223", "quantity" : 21}, {"id" : "332", "quantity" : 3}]
company : {department : {orders -> [{"id" : "222", "quantity" : 8}, {"id" : "663", "quantity" : 3]