鉴于以下BSONDocument
...
val values = BSONDocument("values" -> BSONArray("one", "two", "three"))
如何将其转换为List
?我试过这个......
values.getAs[List[String]]("values").getOrElse(List.empty))
......但它不起作用 - 我总是得到List.empty
。
我错过了什么吗?
修改
好的......我认为值得描述真实案例。我运行了distinct
命令,这就是结果:
values: {
values: [
0: BSONObjectID("55d0f641a100000401b7e454")
],
stats: {
n: BSONInteger(1),
nscanned: BSONInteger(1),
nscannedObjects: BSONInteger(1),
timems: BSONInteger(0),
cursor: BSONString(BtreeCursor projectId_1)
},
ok: BSONDouble(1.0)
}
我需要将values
转换为Scala List[String]
,如下所示:
List("55d0f641a100000401b7e454")
答案 0 :(得分:0)
这是我的解决方案。首先,我已经定义了BSONReader[BSONValue, String]
这样......
package object bsonFormatters {
implicit object BSONValueStringReader extends BSONReader[BSONValue, String] {
def read(bson: BSONValue) = bson match {
case oid: BSONObjectID => oid.stringify
}
}
...然后将其导入我的伴侣对象中,如下所示:
import reactivemongo.bson.{BSONString, BSONDocument}
import reactivemongo.core.commands.{CommandError, BSONCommandResultMaker, Command}
case class Distinct(
collectionName: String,
field: String,
query: Option[BSONDocument] = None
) extends Command[Seq[String]] {
override def makeDocuments = BSONDocument(
"distinct" -> BSONString(collectionName),
"key" -> field,
"query" -> query
)
val ResultMaker = Distinct
}
object Distinct extends BSONCommandResultMaker[Seq[String]] {
import bsonFormatters._ // this makes the trick
def apply(document: BSONDocument) = CommandError.checkOk(
document,
Some("distinct")
).toLeft(
document.getAs[List[String]]("values").getOrElse(List.empty)
)
}
我希望它有所帮助。