此代码选择mongodb集合中的所有元素:
import scala.collection.immutable.IndexedSeq
import org.mongodb.scala._
import org.mongodb.scala.model.Aggregates._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.model.Projections._
import org.mongodb.scala.model.Sorts._
import org.mongodb.scala.model.Updates._
import org.mongodb.scala.model._
import org.mongodb.scala.bson._
object Main extends App {
//http://mongodb.github.io/mongo-scala-driver/1.0/scaladoc/index.html#org.mongodb.scala.bson.collection.immutable.Document
// Use a Connection String
val mongoClient: MongoClient = MongoClient("mongodb://mymongo.com:27017")
// get handle to "mydb" database
val database: MongoDatabase = mongoClient.getDatabase("mydb")
// get a handle to the "test" collection
val collection: MongoCollection[Document] = database.getCollection("mycol")
val observable: FindObservable[Document] = collection.find();
observable.subscribe ( new Observer[Document] {
override def onNext(result: Document): Unit =
{
println(result("question")+"->"+result("answer"))
}
override def onError(e: Throwable): Unit = println("Failed" + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
Thread.sleep(5000)
}
此代码的输出为:
BsonString{value='map1'}->BsonString{value='value1'}
BsonString{value='map2'}->BsonString{value='value2'}
BsonString{value='map3'}->BsonString{value='value3'}
我期待:
map1->value1
map2->value2
map3->value3
我使用Thread.sleep(5000)作为observable.subscribe是非阻塞的,我需要 保持主线程处于活动状态以防止主线程在observable.subscribe之前退出 完成。
为BsonString http://api.mongodb.com/java/current/org/bson/BsonString.html读取api 似乎没有一种方法可以访问价值?
答案 0 :(得分:1)
更换
println(result("question")+"->"+result("answer"))
与
println(result("question").asString.getValue+"->"+result("answer").asString.getValue)
打印预期结果。
result("question")
的结果是BsonValue
,而不是BsonString
。
方法getValue
记录在http://api.mongodb.com/java/3.0/?org/bson/BsonValue.html