[英]How to convert Future[BSONDocument] to list?
The code sends a request to MongoDB using ReactiveMongo and returns Future[BSONDocument]
but my code handles lists of data, so I need to get the value of Future[BSONDocument]
and then turn it into a list. 该代码使用ReactiveMongo向MongoDB发送请求,并返回Future[BSONDocument]
但是我的代码处理数据列表,因此我需要获取Future[BSONDocument]
的值,然后将其转换为列表。
How do I do that preferably without blocking? 我该如何做到最好而不阻塞?
Upadte: Upadte:
I am using ReactiveMongo RawCommand
我正在使用ReactiveMongo 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)))
)))
And the result comes out in Future[BSONDocument]
. 结果显示在Future[BSONDocument]
。 For some simple queries I used default query builder which allowed for simple conversion 对于某些简单查询,我使用默认查询生成器,该生成器允许简单转换
def findLimitedEvents()(implicit ec: ExecutionContext) =
collection.find(BSONDocument.empty)
.query(BSONDocument("tags" -> "lazy"))
.options(QueryOpts().batchSize(10))
.cursor.collect[List](10, true)
I basically I need the RawCommand
output type to match previously used. 基本上,我需要RawCommand
输出类型来匹配以前使用的类型。
Not sure about your exact use-case (showing some more code would help), but it might be useful to convert from List[Future[BSONDocument]]
to one Future[List[BsonDocument]]
, which you can then more easily onSuccess
or map
on, you can do that via: 不确定确切的用例(显示更多代码会有所帮助),但将List[Future[BSONDocument]]
为一个Future[List[BsonDocument]]
可能会很有用,然后您可以更轻松地在onSuccess
或map
,您可以通过以下方式进行操作:
val futures: List[Future[A]] = List(f1, f2, f3)
val futureOfThose: Future[List[A]] = Future.sequence(futures)
You cannot "get" a future without blocking. 您不能无阻碍地“获得”未来。 if you want to wait for a Future
to complete then you must block. 如果要等待Future
完成,则必须阻止。
What you can do is map
a Future
into another Future
: 您可以做的是map
Future
map
到另一个Future
:
val futureDoc: Future[BSONDocument] = ...
val futureList = futureDoc map { doc => docToList(doc) }
Eventually, you'll hit a point where you've combined, mapped, recovered, etc. all your futures and want something to happen with the result. 最终,您将达到一个将所有期货进行组合,映射,恢复等的地步,并希望结果有所作为。 This is where you either block, or establish a handler to do something with the eventual result: 在这里,您可以阻止或建立处理程序以完成最终结果:
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.