我想从Casbah的MongoCollectionBase.find(...)返回的DBObject中提取某个键的值,在这种情况下为“orderItems”。我有解决方案,但我不满意。我发现我的解决方案很麻烦。它在每一步都将从DBObject.toMap返回的java.util.Map转换为Scala Map或其他集合。有什么更好的方法呢?感谢
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]]))
}
删除了详细信息的2行示例数据,这些数据在MongoDB中保留,
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]
答案 0 :(得分:0)
您是否尝试过使用case class
以及Salat?
您还可以查看这个精彩的presentation,特别是幻灯片#28,它会讨论SalatDAO,它允许您直接保留并检索您的案例对象!