3

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

4

1 回答 1

1

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

import play.modules.reactivemongo.json.BSONFormats._
import SomeResult

collection.db.command(command) map { result =>
  result.toSeq map (Json.toJson(_).as[SomeResult])
}

这导致 a 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]
}
于 2013-12-04T14:23:41.150 回答