Skip to content

Aggregation

Info

MongoDB support an easy to use Aggregation Handling.

Demo

Setup imports

scala
import dev.mongocamp.driver.mongodb.Aggregate._
import dev.mongocamp.driver.mongodb._
import dev.mongocamp.driver.mongodb.dao.PersonSpecification

Define stages

scala
val filterStage: Bson = filter(and(equal("gender", "female"), notNullFilter("balance")))

val groupStage: Bson = group(Map("age" -> "$age"), sumField("balance"), firstField("age"))

val sortStage: Bson = sort(sortByKey("age"))

Execute Aggregation

Important

In most cases we have to use the RAW attribute, because the aggregation result not follows the case class pattern. RAW returns always Documents instead of case classes.

scala
val pipeline = List(filterStage, groupStage, sortStage)

val aggregated = PersonDAO.Raw.findAggregated(pipeline).resultList()

Convert Result

For easy result handling, using the implicit Document to Map conversion can be useful.

scala
val list: List[Map[String, Any]] = aggregated

Released under the Apache License 2.0.