Search⌘ K
AI Features

Aggregation Pipeline: Part 2

Explore the MongoDB aggregation pipeline focusing on advanced stages such as $lookup for performing joins with other collections, $limit to restrict results, $skip for pagination, $sort for ordering, and $project to shape query outputs. Understand how to apply these stages to manipulate and optimize your MongoDB query results effectively.

$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.

Markdown
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.

Markdown
db.tasks.aggregate([
{
$match: {
status: "completed",
}
},
{
$lookup: {
from: "users",
localField: "user",
foreignField: "username",
as: "user_profile",
}
},
]);

This returns ...