LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2216 min read

Modeling Many-to-Many Relationships

Model relationships where many documents on each side relate to many on the other, without a relational join table.

The Relational Approach: A Join Table

In a relational database, a many-to-many relationship — like students enrolled in many courses, and courses having many students — needs a separate join table holding pairs of foreign keys.

The MongoDB Approach: Arrays of References

MongoDB typically models this with an array of referenced ids directly on one (or both) sides of the relationship, avoiding a separate join collection for simpler cases.

// students — each holds an array of enrolled course ids
{ "_id": "s1", "name": "Ada", "courseIds": ["c1", "c2"] }
// courses
{ "_id": "c1", "title": "Intro to Databases" }
{ "_id": "c2", "title": "Data Structures" }
db.courses.find({ _id: { $in: ["c1", "c2"] } }); // fetch a student's enrolled courses

Choosing Which Side Holds the Array

Put the array of references on whichever side has a smaller, more bounded count. Since a student enrolls in a manageable number of courses, but a popular course could have thousands of students, courseIds belongs on the student, not studentIds on the course.

Same Logic as One-to-Many

This is really just the one-to-many "few vs. squillions" reasoning applied to both directions of the relationship at once — put the bounded list on the side where it stays small.

A Worked Example: Students & Courses

For genuinely large-scale many-to-many relationships on both sides (millions of users each following millions of other users, for example), a dedicated join-style collection — mirroring the relational approach — can still be the right choice, queried and indexed independently.

// A dedicated collection for a large-scale many-to-many relationship
{ "_id": "e1", "studentId": "s1", "courseId": "c1", "enrolledAt": "2026-01-10" }

FAQs

Yes, though this duplicates the relationship data in two places and requires keeping both arrays in sync — often, holding it on just the smaller/more-bounded side is simpler to maintain.

When the relationship itself has its own data worth storing (like an enrollment date or a role), or when either side of the relationship can grow unboundedly.

Summary

Many-to-many relationships in MongoDB commonly use an array of references on the more bounded side, falling back to a dedicated join-style collection at larger scale. Next, you'll learn schema validation, for enforcing structure even in a flexible-schema database.

Next Lesson →

Schema Validation