Skip to content

HasProject

Pipeline implementing the $project stage.

Inheritors

Properties

context

The context used to generate this pipeline.

Functions

project

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

Specifies a list of fields which should be kept in the document.

All fields (except _id) that are not specified in this stage are unset.

_id is kept even if not specified. To exclude it, see ProjectStageOperators.excludeId.

Difference with $set

This stage and the `$set stage` are quite similar. In fact, both stages behave the same for fields that are specified.

However, the stages behave differently for fields that are not specified:

  • $project removes all fields that are not explicitly specified.

  • $set does not impact fields that are not explicitly specified, they are left in the exact same state as previously.

Performance

When you use a $project stage it should typically be the last stage in your pipeline, used to specify which fields to return to the client.

Using a $project stage at the beginning or middle of a pipeline to reduce the number of fields passed to subsequent pipeline stages is unlikely to improve performance, as the database performs this optimization automatically.

Example

class User(
    val name: String,
    val year: Int?,
)

users.aggregate()
    .project {
        include(User::name)
    }
    .toList()

In this example, the year field will not be returned by the aggregation, because it is not mentioned in the $project stage.

External resources

Parameters

toString

abstract override fun toString(): String

JSON representation of this pipeline.

unsafeCast

abstract fun <New : Any> unsafeCast(): Pipeline<New>

Changes the type of the returned document, with no type-safety.

withStage

Creates a new pipeline that expands on the current one by adding stage.

writeTo

@LowLevelApi
abstract fun writeTo(writer: BsonValueWriter)

Writes the entire pipeline into writer.