🚀 Week 8 Day 4 — Schema Design & Data Relationships in MongoDB
Alright campers 🔥💙
Hope you're doing well and still showing up with curiosity and patience.
Today we answer a very important design question:
How should we structure our data?
Because storing data is easy.
Storing it the right way is what real engineers think about.
🌳 BIG IDEA — MongoDB Is Flexible, But Design Still Matters
MongoDB is called schema-flexible.
That means documents in the same collection do not need identical structure.
Example:
Document 1:
{ "name": "Sara", "age": 22 }Document 2:
{ "name": "John", "email": "john@mail.com", "hobbies": ["music", "sports"] }MongoDB allows this. But here's the important truth: Just because you can store data randomly doesn't mean you should. Good schema design means: ➞Data is easy to read ➞Queries are efficient ➞Relationships are clear ➞The system scales well A good engineer plans the shelves before filling them. 🧱 Two Core Design Approaches in MongoDB MongoDB relationships are handled in two main ways: 1️⃣ Embedding documents 2️⃣ Referencing documents 🟢 1️⃣ Embedding Documents Embedding means placing related data inside the same document. Example: A blog post with its comments.
{ "title": "Learning MongoDB", "author": "Sara", "comments": [ { "user": "John", "message": "Great article!" }, { "user": "Liya", "message": "Very helpful!" } ] }Here, comments are embedded directly inside the post document. ✅ When Embedding Is Good: ➞Data is closely related ➞Data is accessed together ➞The amount of nested data is small Examples: Blog post + comments User profile + address Order + purchased items ⚠️ When Embedding Is Not Ideal: ➡The embedded data grows very large ➡Data must be accessed separately ➡Many documents reference the same data Example problem: If thousands of comments exist, embedding them all inside the post could make the document too large. 🔵 2️⃣ Referencing Documents Referencing means storing related data in separate documents and linking them using IDs. Example: Blog posts referencing users. Users collection:
{ "_id": "user123", "name": "Sara", "email": "sara@mail.com" }Posts collection:
{ "title": "Learning MongoDB", "authorId": "user123" }Here the post stores only the author's ID, not the full user data. ✅ When Referencing Is Good: ➡Data is shared across many documents ➡Data is large ➡Data changes frequently Examples: Users and posts Products and orders Students and courses
17 мар., 04:58
