如何将未来[BSONDocument]转换为列表



代码使用 ReactiveMongo 向 MongoDB 发送请求并返回Future[BSONDocument]但我的代码处理数据列表,所以我需要获取 Future[BSONDocument] 的值,然后将其转换为列表。

我该如何在不阻塞的情况下做到这一点?

乌帕特:

我正在使用反应性Mongo RawCommand

 def findLByDistance()(implicit ec: ExecutionContext) =  db.command(RawCommand(
        BSONDocument(
            "aggregate" -> collName,
            "pipeline" -> BSONArray(BSONDocument(
                "$geoNear" -> BSONDocument(
                    "near" -> BSONArray(44.72,25.365),
                    "distanceField" -> "location.distance",
                    "maxDistance" -> 0.08,
                    "uniqueDocs" -> true)))
                )))

结果在Future[BSONDocument]中出来了.对于一些简单的查询,我使用了默认的查询构建器,它允许简单的转换

def findLimitedEvents()(implicit ec: ExecutionContext) =
  collection.find(BSONDocument.empty)
    .query(BSONDocument("tags" -> "lazy"))
    .options(QueryOpts().batchSize(10))
    .cursor.collect[List](10, true)

基本上我需要RawCommand输出类型来匹配以前使用的类型。

不确定您的确切用例(显示更多代码会有所帮助),但从 List[Future[BSONDocument]] 转换为一个 Future[List[BsonDocument]] 可能会很有用,然后您可以更轻松地onSuccessmap,您可以通过以下方式执行此操作:

val futures: List[Future[A]] = List(f1, f2, f3)
val futureOfThose: Future[List[A]] = Future.sequence(futures)

你不能在不阻止的情况下"获得"未来。 如果要等待Future完成,则必须阻止。

您可以做的是将一个Future map到另一个Future

val futureDoc: Future[BSONDocument] = ...
val futureList = futureDoc map { doc => docToList(doc) }

最终,你会达到一个点,你已经组合、映射、恢复等所有的未来,并希望结果发生一些事情。 这是阻止或建立处理程序以对最终结果执行某些操作的地方:

val futureThing: Future[Thing] = ...
//this next bit will be executed at some later time,
//probably on a different thread
futureThing onSuccess {
  case thing => doWhateverWith(thing)
}

最新更新