如何从此List(String)
获得MongoDBList
?
val a: MongoDBList = ... // equal to [ { "id" : "0001"} , { "id" : "0017"}]
期望的结果:List("0001", "0017")
答案 0 :(得分:0)
MongoDBList扩展scala.collection.mutable.LinearSeq,因此您应该可以使用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)
答案 1 :(得分:0)
我更愿意:
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"))
如果你有
,我不喜欢asInstanceOf{ "data" : [ { "id" : "0001"} , { "id" : "0017"}] }
casbash可以为您序列化Seq
val a2 = MongoDBObject( "data" -> a )
a2.getAs[Seq[DBObject]]("aa").get.map { x => x.getAs[String]("id").get}