Aggregation 源代码
1) Get all records
ticketDB.find(Json.obj("school_bucket" -> "1"))
.cursor[TicketView].collect[List]().map((tickets: List[TicketView]) => Ok(Json.toJson(tickets)))
2) Get distinct field
val distinct = RawCommand(
BSONDocument("distinct" -> "tickets", "key" -> "school_number", "query" -> BSONDocument("school_bucket" -> "1")))
// for distinct, but only return one distinct field
for {
result1 <- db.command(distinct)
} yield {
Ok(toJSON(result1))
}
3) Get first record for each school
// return all fields of the first document for each group
val groupBy = Aggregate("tickets",
Seq(
GroupField("school_number")
(
"id" -> First("id"),
"ticket_number" -> First("ticket_number"),
"school_number" -> First("school_number"),
"school_bucket" -> First("school_bucket"),
"school_name" -> First("school_name")
),
Sort(List(Ascending("id"))),
Match(BSONDocument("school_bucket" -> "1"))
)
)
db.command(groupBy).map(
s => {
val result = s.toList.map(doc => toJSON(doc))
Ok(Json.toJson(result))
}
)
阅读(1027) | 评论(0) | 转发(0) |