Aggregation operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result.

The Aggregation Pipeline

The aggregation pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into aggregated results.

For a full explanation and a complete list of pipeline stages and operators, see the manual:

The following example uses the aggregation pipeline on the restaurants sample dataset.

In the following example, the aggregation pipeline

import MongoKitten

let server = try Server(mongoURL: "mongodb://localhost:27017")
let database = server["tutorial"]

let restaurants = database["restaurants"]

let matchStage = AggregationPipeline.Stage.matching("categories" == "Bakery")
let groupStage = AggregationPipeline.Stage.grouping("$stars", computed: ["count": .sumOf(1)])

let pipeline: AggregationPipeline = [matchStage, groupStage]

let results = try restaurants.aggregate(pipeline: pipeline)

let _ = {