Many-to-Many Modeling
Many-to-Many Modeling: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 34 of 100
Many-to-Many Modeling
Foundations & CRUD ✓ → Queries & Schema → Aggregation & Scale → Atlas & Projects
Queries & Schema · 2 — Design · ~6 min · MongoDB — Schema Design
What is this?
Many-to-many means both sides relate to many of the other — students and courses, products and tags, users and groups. MongoDB often uses arrays of ids on one side, or a join collection when the relationship has metadata.
Why should you care?
A course platform needs “all courses for a user” and “all users in a course”. Arrays work until relationships need progress percent or joinedAt.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.users.insertOne({ _id: 1, name: "Isha", courseIds: [10, 20] })
db.courses.insertMany([
{ _id: 10, title: "MongoDB Basics", studentIds: [1, 2] },
{ _id: 20, title: "Aggregation", studentIds: [1] }
])
// Relationship with metadata
db.enrollments.insertOne({
userId: 1, courseId: 10, progress: 40, enrolledAt: new Date()
})
db.enrollments.find({ userId: 1 })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Arrays of ids are a simple many-to-many.
- enrollments adds progress metadata — better when the link itself has fields.
- Query enrollments by userId to list courses with progress.
Practice next
- Seed users, courses, and one enrollment.
- Find courses for user 1 via courseIds and via enrollments.
- Add progress updates with updateOne on enrollments.
- Query enrollments by courseId to list students.
- Add a unique compound index to prevent double enroll.
Remember
Arrays of ids work for simple M:N. Use a join collection when links have data. Index relationship queries.
NoSQLVerse course enrollments
Learners enroll in many tutorials; each enrollment tracks percent complete.
Outcome: Progress UI reads enrollments without bloating the course catalog doc.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!