1

我的文档如下所示:

{
  "dynamic_field" : "...",
  "another_dynamic_field" : "..."
  "yet_another_dynamic_field" : "..."
}

“动态场”的意思是我不知道它的名字。所以我想获取包含此文档键的字符串集合。然后通过按键获取文档的值(值的结构定义明确)。

因此,我尝试执行以下操作

val dbObject = ... 
val keys = dbObject.keys()
for(
  key <- keys; /java.lang.ClassCastException: com.mongodb.BasicDBList cannot be cast to scala.collection.Seq at this line
  val value = dbObject.as[String](key) /
) yield new MyClass(key, value)

有什么建议么?

4

1 回答 1

1

我不确定你的演员阵容有什么问题,但请确保你在范围内有正确的隐含:

import com.mongodb.casbah.Imports._

我完全不确定“BasicDBList”的来源,但我认为您的迭代过于复杂。只要隐式在范围内,您就可以将 DBObject 直接视为 Scala 对象。这意味着您可以立即迭代其键和值:

scala> val doc = conn("worldDevelopmentIndicators.in").findOne().get
doc: com.mongodb.DBObject = { "_id" : "4ddab3c62511cea643f3e5a0" , "SeriesCode" : "AG.AGR.TRAC.NO" , "Series Name" : "\"Agricultural machinery" , "Country Code" : " tractors\"" , "Country Name" : "AFG" , "1960" : "Afghanistan" , "1962" : 120.0 , "1963" : 150.0 , "1964" : 200.0 , "1965" : 200.0 , "1966" : 300.0 , "1967" : 400.0 , "1968" : 500.0 , "1969" : 500.0 , "1970" : 550.0 , "1971" : 550.0 , "1972" : 600.0 , "1973" : 600.0 , "1974" : 585.0 , "1975" : 570.0 , "1976" : 550.0 , "1977" : 530.0 , "1978" : 515.0 , "1979" : 495.0 , "1980" : 450.0 , "1981" : 400.0 , "1982" : 350.0 , "1983" : 300.0 , "1984" : 250.0 , "1985" : 200.0 , "1986" : 150.0 , "1987" : 150.0 , "1988" : 120.0 , "1989" : 120.0 , "1990" : 120.0 , "1991" : 120.0 , "1992" : 120.0 , "1993" : 110.0 , "1994" : 110.0 , "1995" ...

for ((k,v) <- doc) println(k) 
/*
 _id
 SeriesCode
 Series Name
 Country Code
 Country Name
*/

// you also have the value in this iteration in V...
scala> for (kv <- doc) println(kv) 
(_id,4ddab3c62511cea643f3e5a0)
(SeriesCode,AG.AGR.TRAC.NO)
(Series Name,"Agricultural machinery)
(Country Code, tractors")
(Country Name,AFG)
(1960,Afghanistan)
于 2011-05-24T20:00:17.603 回答