Skip to content

HasLookup

Pipeline implementing the $lookup stage.

Inheritors

Properties

context

The context used to generate this pipeline.

Functions

lookup

Performs an equality match join between this collection and another collection.

For each document in this pipeline, matching documents from the foreign collection are appended into the new array field into. If into already has a value, it is overwritten.

Example

class Department(
    val _id: ObjectId,
    val name: String,
)

class User(
    val _id: ObjectId,
    val name: String,
    val department: ObjectId,
    val departments: List<Department>,
)

users.aggregate()
    .lookup {
        into(User::departments)
        from(departments.aggregate())
        on(User::department, Department::_id)
    }

If you want to store the results in a temporary field (for example, for further processing in a subsequent stage), you can use Field.unsafe to avoid adding the field to the DTO:

class User(
    val _id: ObjectId,
    val name: String,
    val departmentId: ObjectId,
    val department: Department? = null,
)

val temporaryField = Field.unsafe<List<Department>>("departments")

users.aggregate()
    .lookup {
        into(temporaryField)
        from(departments.aggregate())
        on(User::departmentId, Department::_id)
    }
    .project {
        // Write '.department' from the first value returned by the lookup.
        // Because we matched on an _id: ObjectId, we know there can never be multiple results.
        User::department set temporaryField[0]
    }

External resources

Parameters

reinterpret

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

toString

abstract override fun toString(): String

JSON representation of this pipeline.

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.