简体   繁体   English

使用 mongo-scala-driver 在 Scala 中打印来自 Mongodb 的查询结果

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

I'am trying to print results from a MongoDB query in Scala我正在尝试在 Scala 中打印来自 MongoDB 查询的结果

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 .抛出的错误是: 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建议使用mongo-scala-driver version 1.2其他一些问题的答案,因为 printResults() 未在1.1及以下版本中实现

SBT file: SBT文件:

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}]}.信息:ReadPreferenceServerSelector{readPreference=primary} 没有从集群描述 ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]} 选择服务器。 Waiting for 30000 ms before timing out超时前等待 30000 毫秒

Is there any way to view the retrieved results in console?有没有办法在控制台中查看检索到的结果?

You have to include Helpers.scala file to use the printResults() function.您必须包含Helpers.scala文件才能使用printResults()函数。 It is located in their github repository Helpers.scala .它位于他们的 github 存储库Helpers.scala 中

These helper functions waits for the observable to finish before it prints the values.这些辅助函数在打印值之前等待 observable 完成。

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.对我有用的方法是在代码末尾添加一个 Thread.sleep,所以程序在异步调用后结束有机会打印元素。

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.发生这种情况是因为 Mongo 的 Observables 具有反应性,这意味着您必须使用 Futures 来完成大部分操作。

Just the Thread.sleep should work.只有 Thread.sleep 应该可以工作。

Hope it helps!希望有帮助!

MongoDB driver is asynchronous, to make it synchronouse you may apply some of the monads operators MongoDB 驱动程序是异步的,为了使其同步,您可以应用一些 monads 操作符

  1. andThen : Allows the chaining of Observables. andThen :允许链接 Observables。 collect : Collects all the results into a sequence. collect :将所有结果收集到一个序列中。
  2. flatMap : Create a new Observable by applying a function to each result of the Observable. flatMap :通过对 Observable 的每个结果应用一个函数来创建一个新的 Observable。
  3. foldLeft : Creates a new Observable that contains the single result of the applied accumulator function. foldLeft :创建一个新的 Observable,其中包含应用累加器函数的单个结果。 foreach : Applies a function applied to each emitted result. foreach :应用一个函数应用于每个发出的结果。
  4. head : Returns the head of the Observable in a Future. head : 在未来返回 Observable 的头部。
  5. map : Creates a new Observable by applying a function to each emitted result of the Observable. map :通过对 Observable 的每个发出的结果应用一个函数来创建一个新的 Observable。

Full list of observables : 可观察的完整列表:

For example:例如:

val doc = Await.result(myCollection
          .find(and(regex("date", s"^${date}T.*"), equal("field", fieldValue)))
          .sort(descending("timestamp"))
          .first().head(), Duration(10, SECONDS))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM