One-to-Many Modeling
One-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 33 of 100
One-to-Many Modeling
Foundations & CRUD ✓ → Queries & Schema → Aggregation & Scale → Atlas & Projects
Queries & Schema · 2 — Design · ~6 min · MongoDB — Schema Design
What is this?
One-to-many means one parent relates to many children — one user, many orders. In MongoDB you embed when children are few and owned, or reference when children are many or queried alone.
Why should you care?
Wrong choice causes either huge documents or too many joins. Chat rooms (one room, many messages) almost always reference messages in their own collection.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
// One author → many posts (reference + index)
db.users.insertOne({ _id: ObjectId("64a000000000000000000001"), username: "dev" })
db.posts.insertMany([
{ authorId: ObjectId("64a000000000000000000001"), title: "Indexing tips" },
{ authorId: ObjectId("64a000000000000000000001"), title: "Schema tips" }
])
db.posts.createIndex({ authorId: 1, createdAt: -1 })
db.posts.find({ authorId: ObjectId("64a000000000000000000001") })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- The user is one document.
- Posts live in posts with authorId.
- An index on authorId makes “all posts by user” fast.
- This scales better than embedding thousands of posts inside the user.
Practice next
- Insert one user and three posts.
- Query posts by authorId.
- Decide: would you embed comments if max 20 per post? Try both sketches.
- Embed up to 5 recentOrderIds on the user for a dashboard.
- Count posts with countDocuments({ authorId }).
Remember
One-to-many: embed small owned sets, reference large sets. Index the many-side foreign key. Model from how you query.
YouTube-like channel uploads
One channel has millions of videos — videos collection references channelId.
Outcome: Channel profile stays small; video queries paginate independently.
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!