Since MongoDB stores arrays in the same way as JavaScript, like an object with integer keys indicating their index --- BasicDBList is needed to represent the object coming from the wire. Thus, currently Casbah does not automatically represent it as a Scala list .... BasicDBList is a HashMap, not a list.
HOWEVER, inside Casbah does implicit conversions so you can treat BasicDBList as LinearSeq [AnyRef]; LinearSeq is slightly different from the type tree than List, but a more suitable type for various reasons. Unfortunately, you cannot use with implicit conversions.
Currently, I recommend that you get the item as a DBList, and then either enter an annotation in the form of LinearSeq, which will use implicit, or simply call toList (it will implicitly provide the toList method).
scala> val l = MongoDBList("foo", "bar", "baz") l: com.mongodb.BasicDBList = [ "foo" , "bar" , "baz"] scala> val obj = MongoDBObject("list" -> l) obj: com.mongodb.casbah.commons.Imports.DBObject = { "list" : [ "foo" , "bar" , "baz"]} scala> obj.as[BasicDBList]("list") res8: com.mongodb.casbah.Imports.BasicDBList = [ "foo" , "bar" , "baz"] scala> obj.as[BasicDBList]("list").toList res9: List[AnyRef] = List(foo, bar, baz)
The methods as[T]: T and getAs[T]: Option[T] preferable, by the way, for casting, since they have some kind of blende inside to do a type massage. The next release of Casbah will include code, so if you ask for Seq, List, etc., DBList as and getAs will automatically convert them to the type you requested.
Brendan W. McAdams
source share