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
The operators declaring which lookup to perform.
LookupStageOperators.into: Specifies in which field the result will be stored. Mandatory.
LookupStageOperators.from: Specifies the foreign collection.
LookupStageOperators.on: Specifies an equality criteria between a local and a foreign field. Documents are only returned if the value of the two fields is strictly equal.
LookupStageOperators.let: Allow accessing a specific value within
from.