Skip to content

MongoDB request DSLopensavvy.ktmongo.dsl.aggregation.stagesHasUnionWithunionWith

unionWith

Combines two aggregations into a single result set.

$unionWith outputs the combined result set (including duplicates) to the next stage. The order in which the combined result set documents are output is unspecified.

Namespacing

other must be a pipeline from the same namespace. It may be a pipeline from the same collection or another collection, as long as they are both part of the same namespace.

Example

interface Vehicle {
    val brand: String,
}

class Car(
    override val brand: String,
    val enginePower: Int,
) : Vehicle

class Bike(
    override val brand: String,
    val hasBasket: Boolean
)

val selectedCars = cars.aggregate()
    .match { Car::enginePower gt 30 }
    .project { include(Car::brand) }
    .reinterpret<Vehicle>()

val selectedVehicles = bikes.aggregate()
    .project { include(Bike::brand) }
    .reinterpret<Vehicle>()
    .unionWith(selectedCars)
    .limit(5)
    .toList()

External resources