我试图在reactivemongo中实现一个聚合方法,但是我有点卡住了。
我有以下数据集:
{
"_id" : ObjectId("522891aa40ef0b5d11cb9232"),
"created" : 1378390442167,
"origin" : 2,
"originIpAddress" : "",
"rating" : 3,
"remindersSent" : 1,
"status" : 4,
"text" : "",
"updated" : 1378563426223,
"userInfo" : {
"firstName" : "Person",
"lastName" : "Person",
"email" : "[email protected]",
"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" : "[email protected]",
"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" : "[email protected]",
"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
的所有值,可以对其调用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
是一个类似于以下的case类:import play.api.libs.json.Json
case class SomeResult(_id: Long, total: Int)
object SomeResult {
implicit val someResultFormat = Json.format[SomeResult]
}
关于mongodb - 将mongodb聚合函数转换为ReactiveMongo和scala,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19008986/