Scala mongodb: query result as a list

I have successfully inserted data into the mongodb database, but I do not know how to extract data from the query. I use the default Scala Mongodb drive:

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

By the way, the documentation documentation contains errors. This line causes a compilation error when this copy is pasted from a document:

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

This is how I request the collection:

collection.find()

How to convert it to a collection of scala objects that I can iterate over and process? thank

+6
source share
2 answers

, . , "collection.find(). First(). PrintHeadResult()" scala driver 1.1.1. scala github, , - 1.2.0-SNAPSHOT.

, . , . , .

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

+3

, . , casbah, scala, , , , .

, , , , , , (, , ).

API Mongo Scala (2.7.0 ) :

coll.find(Document("head" -> 1)).map(dbo => dbo.getInteger("head"))

, head , map Document (dbo) Int, "head" ( , , . get [T]).

, Observable : https://mongodb.imtqy.com/mongo-scala-driver/2.7/reference/observables/ .

, Observable, - . , , - Await.result .

val e = coll.find(Document("head" -> 1)).map(dbo => dbo.getInteger("head"))
val r = Await.result(e.toFuture(), Duration.Inf)
println(r)

List [Int], Observable.

0

All Articles