set

abstract fun set(block: SetStageOperators<In, Out>.(item: Value<In, Item?>) -> Unit)(source)

Immediately declares a $set stage that follows this $unwind stage.

The output documents have the same fields as the initial documents, except that $set may overwrite some fields.

If you want to create and remove fields, use project 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(
// Fields from 'User'
val _id: ObjectId,
val name: String,

// A single pet
val pet: Pet,
)

users.aggregate()
.unwind {
array(User::pets)

set {
Result::pet set it
}
}

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)