【问题标题】:Returning document as they are added with Scala reactivemongo在使用 Scala reactivemongo 添加时返回文档
【发布时间】:2016-05-25 20:05:58
【问题描述】:

阅读http://reactivemongo.org/releases/0.11/documentation/tutorial/consume-streams.html有这个代码

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

import play.api.libs.iteratee._
import reactivemongo.bson.BSONDocument
import reactivemongo.api.collections.bson.BSONCollection

def processPerson1(collection: BSONCollection, query: BSONDocument): Future[Unit] = {
  val enumeratorOfPeople: Enumerator[BSONDocument] =
    collection.find(query).cursor[BSONDocument].enumerate()

  val processDocuments: Iteratee[BSONDocument, Unit] =
    Iteratee.foreach { person =>
      val lastName = person.getAs[String]("lastName")
      val prettyBson = BSONDocument.pretty(person)
      println(s"found $lastName: $prettyBson")
    }

  enumeratorOfPeople.run(processDocuments)
}

Run 定义为:'驱动迭代器消耗枚举器的输入,在输入的末尾添加一个 Input.EOF。返回结果或异常。来自https://www.playframework.com/documentation/2.5.1/api/scala/index.html#play.api.libs.iteratee.Enumerator 这是否意味着如果将新文档添加到数据库中,则需要再次调用“processPerson1”,以便可以运行enumeratorOfPeople.run(processDocuments) 这一行以便返回它。

我只想在文档被添加到数据库时返回它们而不重新调用相同的代码。可能的“不是很好”的解决方案是将enumeratorOfPeople.run(processDocuments) 包装在预定线程中,但接收所有文件的问题仍然存在,我只想返回尚未返回的文件

【问题讨论】:

  • 不特定于 ReactiveMongo。你应该看看 capoed collections。
  • @cchantep 你的意思是'上限收藏'?

标签: scala reactivemongo


【解决方案1】:

我使用查询创建了一个有上限的 mongo 集合:

db.createCollection("cappedCollection", { "capped": "true", “autoIndexId”:“true”,“size”:4096,“max”:10})

然后在使用find 查询时使用选项:

.options(QueryOpts().tailable.awaitData) - 更多细节:Play + ReactiveMongo: capped collection and tailable cursor

当一个新文档被添加到集合中时,run 方法将返回最新添加的文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多