Aggregation Pipeline: Part 2
Learn and practice the $project, $limit, and $sort aggregation pipelines stages.
$lookup
stage
We use the $lookup
stage to perform the join operations with other collections. This stage performs a left outer join for each input document, and adds a new array
field where the results for the join are added. Next, the transformed documents are sent to the next stage.
We use the below syntax to define the $lookup
stage.
{
$lookup: {
from: <target collection to join to>,
localField: <field of the source document>,
foreignField: <field of the target collection>,
let: <variables to use in pipeline>,
pipeline: <pipeline result is returned on out field>,
as: <output field name>
}
}
To perform the $lookup
stage, we need another collection that will have some referenced data in it. We insert some data into the users
collection.
Press + to interact
db.users.insertMany([{username: "onkar",name: 'Onkar',age: 25,},{username: "shankar",name: 'Shankar',age: 20,}]);
Next, we reference the tasks.user
field to the users.username
field.
Let’s perform a join operation and return the user profile with tasks
.
Press + to interact
db.tasks.aggregate([{$match: {status: "completed",}},{$lookup: {from: "users",localField: "user",foreignField: "username",as: "user_profile",}},]);
This returns the below output.
[
{
_id: ObjectId("6136f1dae5020a122bb6b17c"),
name: 'Learn MongoDB Topic 2',
date: ISODate("2021-09-07T05:00:10.680Z"),
...