Skip to content

opensavvy.ktmongo.dsl.aggregation

Aggregation pipelines are powerful ways to query and update MongoDB documents. Compared to regular queries, aggregation pipelines can perform more complex operations, can compare fields from the same document together, or combine data from other sources.

Aggregation pipelines are declared as a Sequence-like chain of stages. Each stage is responsible for transforming documents in a certain way. MongoDB is able to parallelize work from different stages. To see which stages are available, see Pipeline.

users.aggregate()
    .match {
        // Similar to List.filter
        User::age gt 18
    }
    .project {
        // Select which fields we are interested in.
        // All other fields are ignored.
        include(User::age)
        include(User::name)
    }
    .toList()

Additionally, many stages allow building complex expressions based on different fields. For example, within $set and $project, we can use the $cond operator to conditionally set the value of a field based on other fields:

users.aggregate()
    .set {
        User::risk set cond(
            condition = of(User::isAdult),
            ifTrue = of(User::age) * of(5),
            iFalse = of(18) - of(User::age),
        )
    }
    .toList()

To learn more about aggregation operators and their syntax, see opensavvy.ktmongo.dsl.aggregation.ValueDsl.

You may also be interested in reading the official documentation on aggregations.

Types

AbstractPipeline

abstract class AbstractPipeline<Output : Any>(val context: BsonContext, val chain: PipelineChainLink) : Pipeline<Output> 

Helper class to implement Pipeline.

AbstractValue

@LowLevelApi



abstract class AbstractValue<Root : Any, Type> : Node, Value<Root, Type> 

Utility implementation of Value, which handles the context, toString representation and freezing.

AccumulationOperators

DSL to accumulate values into each other, available in the `$group stage`.

AggregationOperators

DSL to instantiate aggregation values, available in most aggregation stages.

AggregationPipeline

An aggregation pipeline.

Pipeline

interface Pipeline<Output : Any>

A multi-stage pipeline that performs complex operations on MongoDB.

@LowLevelApi



class PipelineChainLink

A single link in the Pipeline chain.

UpdatePipeline

An update pipeline.

Value

interface Value<in Root : Any, out Type> : Node, BsonValueWriteable

An intermediary value in an aggregation expression.