project
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:
$projectremoves all fields that are not explicitly specified.$setdoes 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
The block defining the fields to include.
ProjectStageOperators.include Include a field in the document.
ProjectStageOperators.excludeId Exclude the
_idfield (included by default).ProjectStageOperators.exclude Explicitly exclude a field (all fields are excluded by default).
ProjectStageOperators.set Overwrite the value of a field.
ProjectStageOperators.setIf Overwrite the value of a field if a condition is met.
ProjectStageOperators.setUnless Overwrite the value of a field if a condition is not met.