0
0
MongodbConceptBeginner · 3 min read

One to Many Relationship in MongoDB: Explanation and Example

A one to many relationship in MongoDB means one document is related to many documents in another collection. This is usually handled by storing an array of references or embedding multiple related documents inside a single document.
⚙️

How It Works

Imagine a classroom where one teacher teaches many students. In MongoDB, this is like one document (teacher) connected to many documents (students). You can either keep all student details inside the teacher's document or keep students separate and link them using IDs.

MongoDB allows two main ways to represent this: embedding and referencing. Embedding means putting many related documents inside one document, like a folder with many papers inside. Referencing means keeping documents separate but linking them with IDs, like having a list of student IDs inside the teacher's document.

This flexibility helps you choose the best way based on how you want to access and update your data.

💻

Example

This example shows a teacher document referencing many student documents using their IDs.

mongodb
use school

// Create students collection with two students
db.students.insertMany([
  { _id: 1, name: "Alice", age: 14 },
  { _id: 2, name: "Bob", age: 15 }
])

// Create teacher document referencing students by their IDs
db.teachers.insertOne({
  _id: 101,
  name: "Mr. Smith",
  students: [1, 2]  // references to student _id fields
})

// Query teacher with student references
db.teachers.findOne({ _id: 101 })
Output
{ "_id": 101, "name": "Mr. Smith", "students": [1, 2] }
🎯

When to Use

Use a one to many relationship when one item naturally connects to many others, like a blog post with many comments or a customer with many orders.

Embedding is good when related data is often read together and changes rarely, like a blog post with comments stored inside it.

Referencing is better when related data is large or changes independently, like customers and orders stored separately but linked.

Key Points

  • One to many means one document relates to many documents.
  • Embedding stores related documents inside one document.
  • Referencing stores related documents separately and links by IDs.
  • Choose embedding for fast reads and small related data.
  • Choose referencing for large or frequently changing related data.

Key Takeaways

One to many relationship connects one document to many related documents in MongoDB.
Embedding stores related data inside one document for quick access.
Referencing links separate documents using IDs for flexibility and scalability.
Choose embedding when related data is small and read together.
Choose referencing when related data is large or updated independently.