Skip to content

MongoDB request DSLopensavvy.ktmongo.dsl.aggregation.stagesHasCountcountTo

countTo

open fun <Output : Any> countTo(field: Field<Output, Number>): Pipeline<Output>

Counts how many elements exist in the pipeline and outputs a single document containing a single field containing the count.

field must be a simple field name. Subfields (accessed through the / operator) are forbidden.

Example

class Score(
    val student: ObjectId,
    val subject: String,
    val score: Int,
)

class Results(
    val passingScores: Int,
)

scores.aggregate()
    .match { Score::score gt 99 }
    .countTo(Results::passingScores)

Counts how many elements exist in the pipeline and outputs a single document containing a single field containing the count.

field must be a simple field name. Subfields (accessed through the / operator) are forbidden.

Example

class Score(
    val student: ObjectId,
    val subject: String,
    val score: Int,
)

class Results(
    val passingScores: Int,
)

scores.aggregate()
    .match { Score::score gt 99 }
    .countTo(Results::passingScores)