Example of $lookup with pipeline stages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Traditional $lookup without pipeline | |
*/ | |
UserSchema.aggregate([ | |
{ | |
$lookup: { | |
from: "departments", | |
localField: "department", | |
foreignField: "_id", | |
as: "department", | |
}, | |
}, | |
]); | |
/* | |
* Output: | |
* Whole department document has been populated | |
* We can reduce the number of populated fields to save memory usage | |
*/ | |
// [ | |
// { | |
// _id: "62694214b0f6d30477dbe911", | |
// firstName: "Navanath", | |
// lastName: "Jadhav", | |
// email: "navanath@everblogs.com", | |
// role: "Admin", | |
// department: [{ | |
// _id: "62b315309c9865676e1f2cf1", | |
// __v: 0, | |
// name: "Engineering", | |
// createdAt: "2022-06-22T18:37:07+05:30", | |
// updatedAt: "2022-06-22T18:37:07+05:30", | |
// building: "A", | |
// budget: 10000, | |
// }], | |
// } | |
// ]; | |
/* | |
* $lookup with pipeline stages | |
* We have used $project pipeline stage in $lookup and it allowed us to select only necessary fields | |
*/ | |
UserSchema.aggregate([ | |
{ | |
$lookup: { | |
from: "departments", | |
let: { | |
department_id: "$department", | |
}, | |
pipeline: [ | |
{ | |
$match: { | |
$expr: { | |
$and: [{ $eq: ["$_id", "$$department_id"] }], | |
}, | |
}, | |
}, | |
{ | |
$project: { | |
name: 1, | |
building: 1, | |
budget: 1, | |
}, | |
}, | |
], | |
as: "department", | |
}, | |
}, | |
]); | |
/* | |
* Output: | |
* Only necessary fields have been populated as specified in $project | |
* We have reduced the memory consumption here | |
*/ | |
// [ | |
// { | |
// _id: "62694214b0f6d30477dbe911", | |
// firstName: "Navanath", | |
// lastName: "Jadhav", | |
// email: "navanath@everblogs.com", | |
// role: "Admin", | |
// department: [{ | |
// name: "Engineering", | |
// building: "A", | |
// budget: 10000, | |
// }], | |
// }, | |
// ]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment