此代码从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)作为observate.subscribe是非阻塞的,我需要
使主线程保持活动状态以防止主线程在observate.subscribe之前退出。
完成。
读取bsonstringhttp://api.mongodb.com/java/current/org/bson/BsonString.html的api
似乎没有访问值的方法?
最佳答案
更换
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关于mongodb - 从BsonString中提取String值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41722343/