Skip to content

MongoDB request DSLopensavvy.ktmongo.dsl.aggregation.stagesHasGroupgroup

group

open fun <Out : Any> group(block: AccumulationOperators<Document, Out>.() -> Unit): Pipeline<Out>

Combines multiple documents into a single document.

The resulting documents contain fields generated by accumulating all input documents. To learn more about accumulation operators, see AccumulationOperators.

Example

If we have users with an account balance, we can find out the total account balance of all users.

class User(
    val name: String,
    val balance: Int,
)

class Result(
    val totalBalance: Int,
)

users.aggregate()
    .group {
        Result::totalBalance sum of(User::balance)
    }

To see the list of available accumulation operators, see AccumulationOperators.

Performance

$group is a blocking stage, which causes the pipeline to wait for all input data to be retrieved for the blocking stage before processing the data. A blocking stage may reduce performance because it reduces parallel processing for a pipeline with multiple stages. A blocking stage may also use substantial amounts of memory for large data sets.

External resources