My document looks like this:
{
"dynamic_field" : "...",
"another_dynamic_field" : "..."
"yet_another_dynamic_field" : "..."
}
"Dynamic field" means that I don't know it's name. So I want to get collection of strings which holds keys of this document. Then get values by of document by keys (structure of values are well defined).
So, I tried to do the following
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)
Any suggestions?
I'm not sure what's breaking there as far as your casting goes, but make sure you have the right implicits in scope:
import com.mongodb.casbah.Imports._
I am not sure at all where that "BasicDBList" is coming from, but I think you're overcomplicating your iteration. As long as the implicits are in scope you can treat the DBObject directly as a Scala object. That means you can iterate its keys and values immediately:
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)