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.