我想从 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]