-
-
Save navanathjadhav/0475f9b46dd4d3edd2612f7e40911bd2 to your computer and use it in GitHub Desktop.
Example of $lookup vs populate()
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
/* | |
* 3 Extra DB quries will be made | |
*/ | |
StudentSchema.find() | |
.populate("class") | |
.populate("department") | |
.populate("teacher"); | |
/* | |
* No extra queries, Less load on your Node.js server | |
*/ | |
StudentSchema.aggregate([ | |
{ | |
$lookup: { | |
from: "classes", | |
localField: "class", | |
foreignField: "_id", | |
as: "class", | |
}, | |
}, | |
{ $unwind: "$class" }, | |
{ | |
$lookup: { | |
from: "departments", | |
localField: "department", | |
foreignField: "_id", | |
as: "department", | |
}, | |
}, | |
{ $unwind: "$department" }, | |
{ | |
$lookup: { | |
from: "teachers", | |
localField: "teacher", | |
foreignField: "_id", | |
as: "teacher", | |
}, | |
}, | |
{ $unwind: "$teacher" }, | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment