我正在尝试在ReactiveMongo中实现聚合方法,但我有点卡住了。
我有以下数据集:
{
"_id" : ObjectId("522891aa40ef0b5d11cb9232"),
"created" : 1378390442167,
"origin" : 2,
"originIpAddress" : "",
"rating" : 3,
"remindersSent" : 1,
"status" : 4,
"text" : "",
"updated" : 1378563426223,
"userInfo" : {
"firstName" : "Person",
"lastName" : "Person",
"email" : "person@person.com",
"fbPublish" : false
},
"venueInfo" : {
"isAgent" : false,
"name" : "Company",
"id" : 1234
}
},
{
"_id" : ObjectId("522891aa40ef0b5d11cb9233"),
"created" : 1378390442167,
"origin" : 2,
"originIpAddress" : "",
"rating" : 3,
"remindersSent" : 1,
"status" : 4,
"text" : "",
"updated" : 1378563426223,
"userInfo" : {
"firstName" : "Person2",
"lastName" : "Person2",
"email" : "person2@person.com",
"fbPublish" : false
},
"venueInfo" : {
"isAgent" : false,
"name" : "Company2",
"id" : 4321
}
},
{
"_id" : ObjectId("522891aa40ef0b5d11cb9234"),
"created" : 1378390442167,
"origin" : 2,
"originIpAddress" : "",
"rating" : 3,
"remindersSent" : 1,
"status" : 4,
"text" : "",
"updated" : 1378563426223,
"userInfo" : {
"firstName" : "Person3",
"lastName" : "Person3",
"email" : "person3@person.com",
"fbPublish" : false
},
"venueInfo" : {
"isAgent" : false,
"name" : "Company",
"id" : 1234
}
}
以下聚合函数:
db.reviews.aggregate(
{$match:{status:{"$ne":1}}},
{$group: { _id: "$venueInfo.id", total:{"$sum":1}}}
)
给了我:
{
"result" : [
{
"_id" : 1234,
"total" : 2
},
{
"_id" : 4321,
"total" : 1
}
]
}
我试图在ReactiveMongo中实现这个:
def aggregate() = {
val command = Aggregate(collection.name, Seq(
GroupField("venueInfo.id")("total" -> SumValue(1)),
Match(BSONDocument("status" -> 1))
))
val result = collection.db.command(command)
result.map { value => {
println(s"got value $value")
}
}
这让我:
got value Stream(BSONDocument(<non-empty>), ?)
正如你所看到的,我得到了一个Stream。所以我的问题是:如何以正确的方式处理此流,以便我可以使用这些值并在视图中稍后显示它们?
答案 0 :(得分:1)
如果您想要检索给定Stream
的所有值,可以在其上调用toSeq
或toList
:
import play.modules.reactivemongo.json.BSONFormats._
import SomeResult
collection.db.command(command) map { result =>
result.toSeq map (Json.toJson(_).as[SomeResult])
}
会产生Future[Seq[SomeResult]]
,其中SomeResult
将是一个案例类,如下所示:
import play.api.libs.json.Json
case class SomeResult(_id: Long, total: Int)
object SomeResult {
implicit val someResultFormat = Json.format[SomeResult]
}