Consider the college enrollment system: We have collections for students and classes. How do we register students into classes?
If this were sql, I would make a relator table called enrollment: student.studentid = enrollment.studentid and classes.classid = enrollment.classid.
Lab Learning Outcomes:
How to do this predicate join with mongo db collections
Mongo DB Architect
In the realm of MongoDB, you're dealing with a non-relational, document-oriented database.
This means the approach to data relationships is quite different from traditional SQL databases.
Instead of using a join table like in SQL, you have two primary ways to handle relationships between documents in MongoDB: embedding and referencing (sometimes called linking).
Embedding vs. Referencing
Embedding: This involves nesting related data directly inside a document. For example, you could include an array of class IDs directly in the student document. Referencing (Linking): This is closer to the SQL approach, where you store references (like IDs) to related documents. Here, you would store the class IDs in the student documents or vice versa, similar to foreign keys in SQL. Modeling the College Enrollment System
Given your SQL background, you might find the referencing approach more familiar.
Here's how you can implement it in MongoDB:
Each document in the students collection represents a student, containing their personal information and an array of class IDs they're enrolled in. jsonCopy code
{ "_id": ObjectId("student1"), "name": "Alice Johnson", "enrolledClasses": [ObjectId("class1"), ObjectId("class2")] }
Each document in the classes collection represents a class, containing details about the class. jsonCopy code
{ "_id": ObjectId("class1"), "className": "Introduction to Biology", "instructor": "Dr. Smith" }
Registering a Student into a Class: To register a student for a class, you would add the class's ObjectId to the enrolledClasses array in the student document. shellCopy code
db.students.updateOne( { "_id": ObjectId("student1") }, { $push: { "enrolledClasses": ObjectId("class1") } } );
Querying with Predicate Join
MongoDB provides the $lookup aggregation stage that allows you to perform a join-like operation. For example, to list the classes in which a student is enrolled:
shellCopy code
db.students.aggregate([
{
$lookup: {
from: "classes",
localField: "enrolledClasses",
foreignField: "_id",
as: "classDetails"
}
}
]);
In this query, MongoDB matches the enrolledClasses array from the students collection with the _id field in the classes collection, effectively joining the data.
Considerations
Embedding vs. Referencing: Choose based on your data access patterns and the frequency of updates. Embedding offers faster reads but can make updates more complex. Referencing is more flexible but requires multiple queries or a $lookup to retrieve all related data. Data Redundancy and Normalization: MongoDB allows for greater flexibility in data modeling. Be mindful of data redundancy and the need for data normalization, especially if your data changes frequently. Scalability and Performance: Your choice affects scalability and performance. Test and analyze the performance of your database under realistic conditions to make informed decisions. In summary, while MongoDB doesn't use relational tables, it offers powerful ways to model relationships. The choice between embedding and referencing should be based on your specific use case, considering factors like data structure, query requirements, and performance considerations.
Lab with 10 student records, 4 classes, and the code to assign students to classes
Mongo DB Architect
MongoDB Lab: Managing College Enrollment System
Objective:
This lab exercise aims to demonstrate how to manage a college enrollment system using MongoDB. You will create collections for students and classes, populate them with data, and then assign students to classes.
Part 1: Setting up the Environment
Start MongoDB and Open the Shell: Ensure MongoDB is running and open the MongoDB Shell. shellCopy code
use collegeEnrollmentSystem
Part 2: Creating Collections and Populating Data
Create Students Collection with 10 Student Records: db.students.insertMany([
{ "_id": 1, "name": "Alice Johnson", "age": 20 },
{ "_id": 2, "name": "Bob Smith", "age": 21 },
{ "_id": 3, "name": "Carol Lee", "age": 19 },
{ "_id": 4, "name": "David Brown", "age": 22 },
{ "_id": 5, "name": "Evelyn King", "age": 20 },
{ "_id": 6, "name": "Frank White", "age": 23 },
{ "_id": 7, "name": "Grace Hall", "age": 21 },
{ "_id": 8, "name": "Henry Adams", "age": 20 },
{ "_id": 9, "name": "Irene Walker", "age": 22 },
{ "_id": 10, "name": "Jason Lee", "age": 19 }
]);
Create Classes Collection with 4 Class Records: db.classes.insertMany([
{ "_id": "class1", "className": "Introduction to Biology", "instructor": "Dr. Smith" },
{ "_id": "class2", "className": "Fundamentals of Physics", "instructor": "Dr. Johnson" },
{ "_id": "class3", "className": "World History 101", "instructor": "Dr. Brown" },
{ "_id": "class4", "className": "Literature and Society", "instructor": "Dr. Davis" }
]);
Part 3: Assigning Students to Classes
Assign Students to Classes: For simplicity, assign each student to two classes of your choice. Use the $push operator to add class IDs to the enrolledClasses array in each student document. // Example: Assigning students to classes
db.students.updateOne({ "_id": 1 }, { $push: { "enrolledClasses": { $each: ["class1", "class2"] } } });
db.students.updateOne({ "_id": 2 }, { $push: { "enrolledClasses": { $each: ["class3", "class4"] } } });
// Continue for the rest of the students
Ensure each student is assigned to two different classes. Part 4: Verification and Submission
Use a query to display the students with their enrolled classes. db.students.aggregate([
{
$lookup: {
from: "classes",
localField: "enrolledClasses",
foreignField: "_id",
as: "classDetails"
}
}
]).forEach(printjson);
Document all the commands you used in this lab. Include the output of the verification step. Provide a brief explanation of each step and how the commands work. Grading Criteria:
Correct creation and population of students and classes collections. Accuracy in assigning students to classes. Proper use of MongoDB commands and aggregation for verification. Clarity and completeness of your documentation and explanations. This lab exercise offers hands-on experience with basic MongoDB operations, modeling relationships, and using the aggregation framework. It's designed to enhance your understanding of data management in a non-relational database environment.