Aggregation

Info

MongoDB support an easy to use Aggregation Handling.

Demo

Setup imports

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

Define stages

sourceval 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.

sourceval 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.

sourceval list: List[Map[String, Any]] = aggregated