Skip to content

HasUnwind

Pipeline implementing the $unwind stage.

Inheritors

Properties

context

The context used to generate this pipeline.

Functions

toString

abstract override fun toString(): String

JSON representation of this pipeline.

unsafeCast

abstract fun <New : Any> unsafeCast(): Pipeline<New>

Changes the type of the returned document, with no type-safety.

unwind

open fun <Item, Out : Any> unwind(block: UnwindStageOperators<Document, Item, Out>.() -> Unit): Pipeline<Out>

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

withStage

Creates a new pipeline that expands on the current one by adding stage.

writeTo

@LowLevelApi
abstract fun writeTo(writer: BsonValueWriter)

Writes the entire pipeline into writer.