i am new to MongoDB and Scala language
i am using scala language to connect mongodb locally
i am using below dependency
// https://mvnrepository.com/artifact/org.mongodb.scala/mongo-scala-driver
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "4.2.3"
what I tried
object Demo extends App {
val mongoClient: MongoClient = MongoClient("mongodb://127.0.0.1:27017/")
val database: MongoDatabase = mongoClient.getDatabase("DemoDB")
println(database)
val collection: MongoCollection[Document] =database.getCollection("demodata");
val observable = collection.find();
}
the above code returning the data in below format
FindObservable(com.mongodb.reactivestreams.client.internal.FindPublisherImpl@6253c26)
I also tried with
observable.subscribe ( new Observer[Document] {
override def onNext(result: Document): Unit = println(result.toJson())
override def onError(e: Throwable): Unit = println("Failed" + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
i also tried printResult() and printHeadResult() method also but none of the way is working
please help thanks in advance
Mongo Scala driver works in a non-blocking manner by returning
Observableswhich need to beSubsribedon to consume the published data.When you are subscribing to the
observablelike following,Your code does not wait for
observableto actually publish anything, it just finishes right after subscribing. Hence you don't get anything.You can either add a Something like a
Thread.sleep(5000)at the end to block and give theobeservablesome time to (hopefully finish and) publish the data.Or, you can add
val resultSeq = observable.collectto block and collect all of published data in a single Sequence.