0
0
MongodbConceptBeginner · 4 min read

Many to Many Relationship in MongoDB: Explanation and Example

A many-to-many relationship in MongoDB means that multiple documents in one collection can be related to multiple documents in another collection. This is usually handled by storing arrays of references (IDs) in each document to link them together.
⚙️

How It Works

Imagine you have two groups of things, like students and courses. Each student can take many courses, and each course can have many students. This is a many-to-many relationship.

In MongoDB, which is a document database, you don't have tables like in SQL. Instead, you store documents. To connect many students to many courses, you store lists of references (IDs) inside each document. For example, a student document might have a list of course IDs they are enrolled in, and a course document might have a list of student IDs enrolled.

This way, you can quickly find all courses for a student or all students for a course by looking up these references. It’s like having a list of friends’ phone numbers saved in your phone contacts to call them anytime.

💻

Example

This example shows two collections: students and courses. Each student has an array of courseIds, and each course has an array of studentIds to represent the many-to-many relationship.

mongodb
db.students.insertMany([
  { _id: 1, name: "Alice", courseIds: [101, 102] },
  { _id: 2, name: "Bob", courseIds: [102, 103] }
]);

db.courses.insertMany([
  { _id: 101, title: "Math", studentIds: [1] },
  { _id: 102, title: "Science", studentIds: [1, 2] },
  { _id: 103, title: "History", studentIds: [2] }
]);

// Query: Find courses for Alice
const alice = db.students.findOne({ name: "Alice" });
const aliceCourses = db.courses.find({ _id: { $in: alice.courseIds } }).toArray();
printjson(aliceCourses);

// Query: Find students in Science course
const science = db.courses.findOne({ title: "Science" });
const scienceStudents = db.students.find({ _id: { $in: science.studentIds } }).toArray();
printjson(scienceStudents);
Output
[ { "_id" : 101, "title" : "Math", "studentIds" : [ 1 ] }, { "_id" : 102, "title" : "Science", "studentIds" : [ 1, 2 ] } ] [ { "_id" : 1, "name" : "Alice", "courseIds" : [ 101, 102 ] }, { "_id" : 2, "name" : "Bob", "courseIds" : [ 102, 103 ] } ]
🎯

When to Use

Use many-to-many relationships in MongoDB when you have two sets of data that can relate to each other in multiple ways. For example:

  • Students and courses, where students can enroll in many courses and courses have many students.
  • Authors and books, where authors can write multiple books and books can have multiple authors.
  • Tags and blog posts, where posts can have many tags and tags can belong to many posts.

This approach helps keep your data flexible and easy to query without duplicating information.

Key Points

  • Many-to-many relationships link multiple documents in two collections.
  • Use arrays of references (IDs) in documents to connect them.
  • This method avoids data duplication and keeps relationships clear.
  • Queries use $in operator to find related documents.
  • Good for flexible, real-world relationships like students-courses or tags-posts.

Key Takeaways

Many-to-many relationships in MongoDB use arrays of references in documents to link collections.
Store IDs of related documents in arrays to represent connections both ways if needed.
Use the $in operator to query documents related through these references.
This pattern fits real-world cases like students and courses or tags and posts.
It keeps data flexible and avoids duplication while allowing easy lookups.