Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala mongodb : result of query as list

Tags:

mongodb

scala

I successfully inserted data into a mongodb database, but I don't know how to extract data out of a query. I use the default scala mongodb drive :

"org.mongodb.scala" %% "mongo-scala-driver" % "1.1.1"

The documentation seems to contains errors, by the way. This line rises a compilation error while this is copy pasted from the doc :

collection.find().first().printHeadResult()

This is how I query a collection:

collection.find()

How to convert it to a scala collection of object on which I can iterate and process ? Thanks

like image 795
Moebius Avatar asked May 30 '16 21:05

Moebius


1 Answers

Yes, I agree with the compilation error. I think "collection.find().first().printHeadResult()" is not part of scala driver 1.1.1 release. The current scala driver github which uses this code is "1.2.0-SNAPSHOT" version.

You can get the results using the below code. However, you may experience some async behavior using the below code. Please refer the driver documentation.

val observable: FindObservable[Document] = collection.find();
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")
})

Mongo driver Observables link

like image 149
notionquest Avatar answered Nov 15 '22 05:11

notionquest