Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing query results from Mongodb in Scala using mongo-scala-driver

I'am trying to print results from a MongoDB query in Scala

val mongoClient: MongoClient = MongoClient()
val database: MongoDatabase = mongoClient.getDatabase("tableScala")
val collection: MongoCollection[Document] = database.getCollection("tableScala")

collection.find().printResults()

The error thrown was : Cannot resolve symbol printResults. Answers to some other questions suggested to use mongo-scala-driver version 1.2, as printResults() is not implemented for version 1.1 and below

SBT file:

name := "scalaMongoDriver"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "1.2.0-beta1"

Tried to print manually using :

collection.find().subscribe(
      (user: Document) => println(user.toJson()),                         // onNext
      (error: Throwable) => println(s"Query failed: ${error.getMessage}"), // onError
      () => println("Done")                                               // onComplete
    ) 

resulted in the following info:

INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out

Is there any way to view the retrieved results in console?

like image 446
vdep Avatar asked Dec 24 '22 23:12

vdep


2 Answers

You have to include Helpers.scala file to use the printResults() function. It is located in their github repository Helpers.scala.

These helper functions waits for the observable to finish before it prints the values.

like image 189
Luke Kroon Avatar answered May 18 '23 13:05

Luke Kroon


I had the same problem today, but I found a solution on the web.

The way that worked for me was adding a Thread.sleep in the end of the code, so the program end after the asynchronous call has the chance to print the elements.

This happens because of the reactive nature of Mongo's Observables, meaning that you have to do most of your operations making the use of Futures.

Just the Thread.sleep should work.

Hope it helps!

like image 24
carvalh0ak Avatar answered May 18 '23 13:05

carvalh0ak