array

abstract fun array(field: Field<In, Collection<Item>?>)(source)
open fun array(field: KProperty1<In, Collection<Item>?>)(source)

The array to be unwound.

Each document that contains the specified array will be duplicated the number of times of the array's length. Each generated document is identical to the original except that the specified array is replaced by an array of size 1 that corresponds to one of the items of the array.

For more information, see $unwind.

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)

External resources