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:
Prerequisites: Basic knowledge of MongoDB and JavaScript
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 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
}
// Create a new user with embedded orders
db.users.insertOne({
name: "John Doe",
orders: [
{product: "Apple", quantity: 3},
{product: "Banana", quantity: 2}
]
});
// 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
});
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
Create a data model for a blog. Each blog post has comments. Would you use embedding or referencing?
Create a data model for a social media site. Each user has a list of friends. Would you use embedding or referencing?
Create a data model for a large e-commerce site. Each product has reviews. Would you use embedding or referencing?
Solutions:
Embedding. Comments are typically retrieved with the blog post and are small in size.
Referencing. The list of friends could be large and is not always retrieved with the user.
Referencing. Reviews could be large and are not always retrieved with the product.