Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created June 21, 2022 15:43
Embed
What would you like to do?
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