MongoDB / Schema Design and Data Modeling

Choosing Between Embedding and Referencing

In this tutorial, we'll explore the concepts of embedding and referencing in MongoDB and provide guidance on when to use each technique.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores best practices for designing efficient schemas and data models in MongoDB.

Choosing Between Embedding and Referencing

1. Introduction

In this tutorial, we will discuss the two primary methods of relating documents in MongoDB: Embedding and Referencing. We will discuss when to use each technique and provide clear examples and guidance.

By the end of this tutorial, you will be able to:

  • Understand the concepts of Embedding and Referencing in MongoDB
  • Choose the appropriate method for your data model
  • Implement each method in your applications

Prerequisites: Basic knowledge of MongoDB and JavaScript

2. Step-by-Step Guide

Embedding

In MongoDB, embedding means storing related data in a single document, typically in an array. This is useful if you always retrieve the related data together, as it minimizes the number of database calls.

Example:

{
    name: "John Doe",
    orders: [
        {product: "Apple", quantity: 3},
        {product: "Banana", quantity: 2}
    ]
}

Referencing

Referencing involves storing the ObjectId of one document in another. This is useful if the related data is not always retrieved together, or if the related data is large and would exceed MongoDB's document size limit (16MB).

Example:

//User Document
{
    _id: ObjectId("507f191e810c19729de860ea"),
    name: "John Doe"
}

//Order Document
{
    userId: ObjectId("507f191e810c19729de860ea"),
    product: "Apple",
    quantity: 3
}

3. Code Examples

Embedding Example

// Create a new user with embedded orders
db.users.insertOne({
    name: "John Doe",
    orders: [
        {product: "Apple", quantity: 3},
        {product: "Banana", quantity: 2}
    ]
});

Referencing Example

// Create a new user
let result = db.users.insertOne({name: "John Doe"});

// Create a new order referencing the user
db.orders.insertOne({
    userId: result.insertedId,
    product: "Apple",
    quantity: 3
});

4. Summary

In this tutorial, we discussed the concepts of Embedding and Referencing in MongoDB and provided examples of each. As a rule of thumb, use embedding if your related data is always retrieved together and is small in size. Use referencing if your related data is rarely retrieved together or is large in size.

Further Reading: MongoDB Documentation

5. Practice Exercises

  1. Create a data model for a blog. Each blog post has comments. Would you use embedding or referencing?

  2. Create a data model for a social media site. Each user has a list of friends. Would you use embedding or referencing?

  3. Create a data model for a large e-commerce site. Each product has reviews. Would you use embedding or referencing?

Solutions:

  1. Embedding. Comments are typically retrieved with the blog post and are small in size.

  2. Referencing. The list of friends could be large and is not always retrieved with the user.

  3. Referencing. Reviews could be large and are not always retrieved with the product.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

File Size Checker

Check the size of uploaded files.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Image Converter

Convert between different image formats.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help