2013-09-25 53 views
2

我试图在ReactiveMongo中实现一个聚合方法,但是我有点卡住了。将mongodb聚合函数转换为ReactiveMongo和scala

我有以下数据集:

{ 
    "_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>), ?) 

正如你看到的,我收到了流回来。所以我的问题是:如何以正确的方式处理这个流,以便我可以使用这些值并在视图中稍后显示它们?

+0

我想在你的代码的匹配是不正确的,在样本数据存在与状态没有行= 1 匹配(BSONDocument(“状态” - > BSONDocument(“$ NE” - > 1)))也许是正确的 – barczajozsef

回答

1

如果你想获取给定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将是一个case类像下面这样:

import play.api.libs.json.Json 

case class SomeResult(_id: Long, total: Int) 

object SomeResult { 
    implicit val someResultFormat = Json.format[SomeResult] 
}