project
Immediately declares a $project stage that follows this $unwind stage.
The output documents have the fields declared in the projection. Fields not declared are removed (except _id).
If you want to only overwrite fields, use set instead. project is more verbose, but also more performant since it guarantees there are no left-over unused fields.
Using both project and set in the same $unwind is forbidden.
The benefit of using this method instead of manually declaring a subsequent projection is that this method receives the correctly-typed variable that contains the unwind result.
The field passed to array should not be used within the projection, as it has been unwound and thus doesn't store an array anymore: its type is incorrect within this stage.
Example
class User(
val _id: ObjectId,
val name: String,
val pets: List<Pet>
)
class Pet(
val name: String,
val age: Int,
)
class Result(
val userId: ObjectId,
val userName: String,
val petName: String,
val petAge: Int,
)
users.aggregate()
.unwind {
array(User::pets)
project {
Result::userId set User::name
Result::userName set User::name
Result::petName set (it / Pet::name)
Result::petAge set (it / Pet::age)
}
}Example input:
User(/* … */, "Alice", listOf(Pet("Bob", 5), Pet("Charlie", 6)))
User(/* … */, "Damian", listOf(Pet("Eva", 2)))Output:
Result(/* … */, "Alice", "Bob", 5)
Result(/* … */, "Alice", "Charlie", 6)
Result(/* … */, "Damian", "Eva", 2)