0
0
MongoDBquery~5 mins

Embedding vs referencing decision in MongoDB

Choose your learning style9 modes available
Introduction

Embedding and referencing help organize related data in MongoDB. Choosing between them affects how easy and fast it is to get your data.

When you want all related information together for quick access, like a blog post with its comments.
When data changes often and you want to avoid updating many places, like user profiles linked to orders.
When data is large or shared by many, so you want to keep it separate to save space, like product details used in many orders.
When you want to keep your data simple and avoid complex queries, embedding small related data helps.
When you expect to grow your data a lot, referencing helps keep things organized and scalable.
Syntax
MongoDB
Embedding example:
{
  _id: ObjectId("..."),
  name: "Alice",
  address: {
    street: "123 Main St",
    city: "Townsville"
  }
}

Referencing example:
{
  _id: ObjectId("..."),
  name: "Alice",
  address_id: ObjectId("...")
}

Address document:
{
  _id: ObjectId("..."),
  street: "123 Main St",
  city: "Townsville"
}

Embedding stores related data inside the same document.

Referencing stores related data in separate documents and links them by ID.

Examples
Embedding author details inside the book document for quick access.
MongoDB
{
  _id: 1,
  name: "Book",
  author: {
    name: "John Doe",
    age: 45
  }
}
Referencing author by ID to keep author data separate and reusable.
MongoDB
{
  _id: 1,
  name: "Book",
  author_id: 101
}

{
  _id: 101,
  name: "John Doe",
  age: 45
}
Sample Program

This example shows embedding author info inside a book document. When we get the book, we get author details too.

MongoDB
db.books.insertOne({
  _id: 1,
  title: "MongoDB Guide",
  author: {
    name: "Jane Smith",
    email: "jane@example.com"
  }
})

const book = db.books.findOne({_id: 1})
printjson(book)
OutputSuccess
Important Notes

Embedding is good for data that belongs together and changes together.

Referencing is better when data is large, shared, or changes independently.

Think about how you will read and update your data to choose the best method.

Summary

Embedding stores related data inside one document for fast access.

Referencing links documents by ID to keep data separate and reusable.

Choose embedding for small, tightly related data; choose referencing for large or shared data.