Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created June 24, 2022 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navanathjadhav/b91424019703dab5ecc76cbe14c69650 to your computer and use it in GitHub Desktop.
Save navanathjadhav/b91424019703dab5ecc76cbe14c69650 to your computer and use it in GitHub Desktop.
Example of $lookup with pipeline stages
/*
* 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