Is it possible to add a pipeline to the arguments of another pipeline in mongodb?
An example of the current result that I am getting: MongoPlayground
Is it possible to project the emp table to only name and email field before adding it to the lookup pipeline as an argument? The result that I want:
[
{
"_id": ObjectId("610bce417b0c4008346547bc"),
"employees": [
{
"email": "[email protected]",
"name": "xyz"
}
],
"name": "Chicago",
"number": 10
}
]
You are almost there. What you seek is the pipeline version of $lookup
:
db.dept.aggregate([
{$lookup: {"from": "emp",
let: { did: "$_id" },
pipeline: [
{$match: {$expr: {$eq: [ "$_id", "$$did" ]} }},
{$project: {
_id:false,
email:true,
name:true
}}
],
as: "employees"
}}
]);
which will yield:
{
"_id" : 0,
"name" : "Chicago",
"number" : 10,
"employees" : [
{
"name" : "xyz",
"email" : "[email protected]"
}
]
}