This code selects all elements from a mongodb collection :
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)
}
The output of this code is :
BsonString{value='map1'}->BsonString{value='value1'}
BsonString{value='map2'}->BsonString{value='value2'}
BsonString{value='map3'}->BsonString{value='value3'}
I'm expecting :
map1->value1
map2->value2
map3->value3
I'm using Thread.sleep(5000) as observable.subscribe is non blocking and I need to keep main thread alive to prevent main thread exiting before the observable.subscribe completes.
Reading the api for BsonString http://api.mongodb.com/java/current/org/bson/BsonString.html there does not appear to be a method to access value ?
Replacing
println(result("question")+"->"+result("answer"))
with
println(result("question").asString.getValue+"->"+result("answer").asString.getValue)
prints expected result.
The result of result("question") is BsonValue , not BsonString.
The method getValue is documented at http://api.mongodb.com/java/3.0/?org/bson/BsonValue.html