Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created June 21, 2022 15:43
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/0475f9b46dd4d3edd2612f7e40911bd2 to your computer and use it in GitHub Desktop.
Save navanathjadhav/0475f9b46dd4d3edd2612f7e40911bd2 to your computer and use it in GitHub Desktop.
Example of $lookup vs populate()
/*
* 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