Extract Data from MongoDBList

422 Views Asked by At

How can I get a List(String) from this MongoDBList?

val a: MongoDBList = ... // equal to [ { "id" : "0001"} , { "id" : "0017"}]

Desired result: List("0001", "0017")

2

There are 2 best solutions below

2
On

MongoDBList extends scala.collection.mutable.LinearSeq so you should be able to to use toList

val bld = MongoDBList.newBuilder

bld += MongoDBObject("id" -> "0001")
bld += MongoDBObject("id" -> "0017")

val a = bld.result

val l = for( o <- a.toList )
  yield JSON.parse(o.toString).asInstanceOf[DBObject].get("id")

println(l)

//output
//List(0001, 0017)
0
On

I would prefer:

val bld = MongoDBList.newBuilder

bld += MongoDBObject("id" -> "0001")
bld += MongoDBObject("id" -> "0017")

val a = bld.result

a.map(x=> x.asInstanceOf[DBObject].getAs[String]("id").get)
// or to avoid nonexitence emelents
a.flatMap(x=> x.asInstanceOf[DBObject].getAs[String]("id"))

I don't like asInstanceOf here if you have

{ "data" : [ { "id" : "0001"} , { "id" : "0017"}] }

casbash can serialize Seq for you

val a2 = MongoDBObject( "data" -> a )
a2.getAs[Seq[DBObject]]("aa").get.map { x => x.getAs[String]("id").get}