MONGODB Tutorial



MongoDB RELATIONSHIP


🔗 MongoDB Relationships

Unlike traditional SQL databases that use joins to relate data across tables, MongoDB handles relationships differently. Since MongoDB stores data in flexible, schema-less JSON-like documents, relationships are usually managed using:

  • Embedded Documents (like nested objects)
  • References (like foreign keys using _id)

📌 1. Embedded Documents (One-to-One / One-to-Many)

Best when related data is frequently accessed together. In this method, one document contains another inside it.

{
  _id: 1,
  name: "John",
  address: {
    street: "123 Main St",
    city: "New York"
  }
}
  

📌 2. Referenced Documents (One-to-Many / Many-to-Many)

Used when documents grow large or data is shared across collections. Reference another document using its _id.

// users collection
{
  _id: 101,
  name: "Alice"
}

// orders collection
{
  _id: 5001,
  userId: 101,
  product: "Laptop"
}
  

🔍 Retrieving Data with Reference

To fetch related data, you can use the $lookup stage in aggregation (similar to JOIN):

db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "userDetails"
    }
  }
])
  
Tip: Use embedded documents when data is tightly coupled. Use references when data needs to scale or is shared.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review