使用 Casbah,我查询 Mongo。
val mongoClient = MongoClient("localhost", 27017)
val db = mongoClient("test")
val coll = db("test")
val results: MongoCursor = coll.find(builder)
var matchedDocuments = List[DBObject]()
for(result <- results) {
matchedDocuments = matchedDocuments :+ result
}
然后,我List[DBObject]
通过以下方式将其转换为 JSON:
val jsonString: String = buildJsonString(matchedDocuments)
有没有更好的方法将“结果”(MongoCursor
)转换为 JSON(JsValue
)?
private def buildJsonString(list: List[DBObject]): Option[String] = {
def go(list: List[DBObject], json: String): Option[String] = list match {
case Nil => Some(json)
case x :: xs if(json == "") => go(xs, x.toString)
case x :: xs => go(xs, json + "," + x.toString)
case _ => None
}
go(list, "")
}