1

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

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

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

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

2 Answers2

0

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)
David Holbrook
  • 1,617
  • 14
  • 18
  • Hi David - when I try that, I get `List({ "id" : "0001"}, { "id" : "0017"})`. After getting this result, I suppose I need to convert each item to a `JsValue`, and then parse via `val idVal = (listElementJson \ "id").asOpt[String]`? – Kevin Meredith Sep 09 '13 at 13:37
  • I didn't quite follow what you were asking, answer is updated to reflect actual question – David Holbrook Sep 09 '13 at 18:54
0

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}
Oleg
  • 3,080
  • 3
  • 40
  • 51