gpt4 book ai didi

mongodb - 将 mongodb 聚合函数转换为 ReactiveMongo 和 scala

转载 作者:可可西里 更新时间:2023-11-01 10:44:10 26 4
gpt4 key购买 nike

我正在尝试在 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。所以我的问题是:如何以正确的方式处理这个流,以便我可以处理这些值并稍后在 View 中显示它们?

最佳答案

如果您想检索给定 Stream 的所有值,您可以对其调用 toSeqtoList:

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]
}

关于mongodb - 将 mongodb 聚合函数转换为 ReactiveMongo 和 scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com