unwind
Unwinds an array.
The array is specified with the array keyword, which is mandatory.
Unwinding
Unwinding an array means duplicating the root document the same number of times as there are array items, replacing the array in each copy by one of its items.
For example, if the following document is an input:
{
"a": 1,
"b": 2,
"c": [3, 4, 5]
}and we unwind the array "c", then the output will be three documents:
{
"a": 1,
"b": 2,
"c": 3
}{
"a": 1,
"b": 2,
"c": 4
}{
"a": 1,
"b": 2,
"c": 5
}Each output document is a copy of the original document, but with the array replaced by one of its items.
Example
class User(
val _id: ObjectId,
val name: String,
val pets: List<Pet>,
)
class Pet(
val name: String,
val age: Int,
)
class UserPet(
// …the fields from User you're interested in…
val _id: ObjectId,
val name: String,
// …a single pet instead of the array.
val pet: Pet,
)
users.aggregate()
.unwind {
// Unwind the 'pets' array
array(User::pets)
// Immediately project the unwinding result into the new field 'pet'
project {
UserPet::pet set it
}
}External resources
See also
The operators declaring how the array should be unwound.
UnwindStageOperators.array: Specifies which array will be unwound. Mandatory.
UnwindStageOperators.writeArrayIndexTo: Specifies a new field into which the index of the current unwound item will be stored.
UnwindStageOperators.preserveNullAndEmptyArrays: Specifies how to behave in the presence of
null, a missing field, or an empty array.UnwindStageOperators.project: Specifies an immediate projection (declaring which fields to keep), which has access to the result of the unwinding.
UnwindStageOperators.set: Specifies an immediate projection (declaring which fields to overwrite), which has access to the result of the unwinding.