Inserting sample data:
db.students.insertMany([
{
_id: "1",
name: "Joe",
degree: "physics"
},
{
_id: "2",
name: "Cindy",
degree: "Business"
},
{
_id: "3",
name: "Joey",
degree: "Math"
},
{
_id: "4",
name: "Cynthia",
degree: "Chemical Engineering"
},
{
_id: "5",
name: "Marilyn",
degree: "Biology"
},
{
_id: "6",
name: "Mason",
degree: "Basket Weaving"
},
{
_id: "7",
name: "Irina",
degree: "physics"
},
{
_id: "8",
name: "Austin",
degree: "Business"
}
])
db.classes.insertMany([
{
_id: "1",
teacher: "ms. Tilson",
title: "Physics 101",
},
{
_id: "2",
teacher: "mr. Thedell",
title: "Math 101",
},
{
_id: "3",
teacher: "ms. Fallen",
title: "Math 260",
},
{
_id: "4",
teacher: "ms. Edwards",
title: "Creative Writing",
},
{
_id: "5",
teacher: "mr. Sanders",
title: "Accounting 101",
},
{
_id: "6",
teacher: "ms. Roosevelt",
title: "Welding",
},
{
_id: "7",
teacher: "mr. Tyson",
title: "Yoga",
}
]);
db.students_classes.insertMany([
{
_id: "1",
student_id: "1",
class_id: "1",
},
{
_id: "2",
student_id: "1",
class_id: "2",
},
{
_id: "3",
student_id: "1",
class_id: "3",
},
{
_id: "4",
student_id: "1",
class_id: "4",
},
{
_id: "5",
student_id: "1",
class_id: "5",
},
{
_id: "6",
student_id: "1",
class_id: "6",
},
{
_id: "7",
student_id: "1",
class_id: "7",
},
{
_id: "8",
student_id: "2",
class_id: "1",
},
{
_id: "9",
student_id: "2",
class_id: "3",
},
{
_id: "10",
student_id: "2",
class_id: "6",
},
{
_id: "11",
student_id: "2",
class_id: "7",
},
{
_id: "12",
student_id: "3",
class_id: "4",
},
{
_id: "13",
student_id: "3",
class_id: "6",
},
{
_id: "14",
student_id: "4",
class_id: "2",
},
{
_id: "15",
student_id: "4",
class_id: "3",
},
{
_id: "16",
student_id: "4",
class_id: "4",
},
{
_id: "17",
student_id: "5",
class_id: "1",
},
{
_id: "18",
student_id: "5",
class_id: "5",
},
{
_id: "19",
student_id: "5",
class_id: "7",
},
{
_id: "20",
student_id: "6",
class_id: "3",
},
{
_id: "21",
student_id: "6",
class_id: "5",
},
{
_id: "22",
student_id: "7",
class_id: "6",
},
{
_id: "23",
student_id: "7",
class_id: "7",
},
{
_id: "24",
student_id: "7",
class_id: "3",
}
])
// Connect students table to the students_classes table to see
// all the IDs of the classes the student is enrolled in
db.students.aggregate(
[
{
$lookup:
{
from: "students_classes",
localField: "_id",
foreignField: "student_id",
as: "class_ids"
}
}
]
)
// step 2. Take all the class_ids of the classes the student is taking, and join those onto the classes table, creating a many to many relationship between students and classes.
db.students.aggregate(
[
{
$lookup:
{
from: "students_classes",
localField: "_id",
foreignField: "student_id",
as: "class_ids"
}
},
{
$lookup:
{
from: "classes",
localField: "class_ids.class_id",
foreignField: "_id",
as: "current_classes"
}
}
]
)