MongoDB Schema Design: Embedding vs Referencing — When to Use Each
Designing a MongoDB schema is more than deciding which fields belong in a document. One of the most important decisions is how to represent relationships between related pieces of data.
Consider an e-commerce application. A customer can have multiple addresses, an order contains multiple products, and a product can belong to several categories. Should all this information live inside a single document, or should each entity have its own collection?
MongoDB gives you two primary approaches:
- Embedding: Store related information inside the same document.
- Referencing: Store related information in separate documents and connect them using identifiers.
Both approaches are useful, but choosing the wrong one can lead to unnecessarily large documents, expensive queries, complicated updates, and scalability problems.
In this guide, we'll explore both approaches, compare their trade-offs, and learn how to choose an appropriate schema design for real-world applications.
1. Understanding Relationships in MongoDB
Before choosing between embedding and referencing, understand how your application's data is related.
Most application relationships fall into three categories:
| Relationship | Description | Example |
|---|---|---|
| One-to-one | One entity is associated with one other entity | User and profile |
| One-to-many | One entity is associated with multiple entities | Blog post and comments |
| Many-to-many | Multiple entities can be associated with multiple other entities | Students and courses |
MongoDB doesn't require you to model these relationships exactly like a relational database.
Instead, you can organize related information according to how your application reads, writes, and updates it.
For example, if a page always displays a user's basic profile information together with their account settings, storing those fields in one document may be convenient.
However, if a user can create thousands of independently managed records, putting all those records into one document may not be a good design.
This is where embedding and referencing become important.
2. What Is Embedding in MongoDB?
Embedding means storing related information directly inside a parent document as nested objects or arrays.
For example, consider a user with profile information and account settings.
Instead of creating separate collections for the user, profile, and settings, you can store everything together:
{
_id: ObjectId("65f123456789abcdef123456"),
name: "Robin",
email: "[email protected]",
profile: {
bio: "MERN Stack Developer",
location: "India",
website: "https://example.com"
},
settings: {
theme: "dark",
notifications: true,
language: "en"
}
}
Here, profile and settings are embedded documents.
You can retrieve the user and the related information using one database operation:
const user = await User.findById(userId);
You don't need to query separate collections to retrieve the profile and settings.
Advantages of embedding
1. Fewer database operations
Related information can be retrieved in a single query instead of making multiple queries or using $lookup.
2. Better read efficiency for related data
When an application frequently accesses related fields together, embedding can reduce the work required to retrieve them.
3. Atomic updates within a document
MongoDB guarantees atomicity at the single-document level. Changes to multiple embedded fields in one document are applied atomically.
4. Simpler application logic
You don't need to manually resolve references for information already available inside the parent document.
Disadvantages of embedding
Embedding isn't suitable for every relationship.
Potential problems include:
- Documents can become unnecessarily large.
- Unbounded arrays can continuously increase document size.
- Frequently updated duplicated data can become difficult to maintain.
- Retrieving a large document when only a small portion is needed can waste bandwidth and memory.
- A document cannot exceed MongoDB's 16 MiB BSON document size limit.
Embedding works best when related information is relatively small, has a predictable size, and is commonly accessed together.
3. What Is Referencing in MongoDB?
Referencing means storing related information in separate documents and connecting them using identifiers.
For example, consider a user and their blog posts.
Instead of storing every post inside the user document, you can maintain separate users and posts collections.
Users collection:
{
_id: ObjectId("65f123456789abcdef123456"),
name: "Robin",
email: "[email protected]"
}
Posts collection:
{
_id: ObjectId("65f987654321abcdef654321"),
title: "Getting Started with MongoDB",
content: "MongoDB is a document-oriented database...",
author: ObjectId("65f123456789abcdef123456")
}
The author field stores the user's ObjectId.
To retrieve the posts belonging to a user, query the posts collection:
const posts = await Post.find({
author: userId
});
The user and posts remain independent documents, but the application can connect them through their identifiers.
Advantages of referencing
1. Independent data management
Each entity can be created, updated, and deleted independently.
2. Better handling of large relationships
A user with thousands of posts doesn't need to store all those posts inside one document.
3. Reduced duplication
When multiple documents need to access the same entity, they can reference one shared document instead of duplicating its complete data.
4. Independent querying
You can retrieve posts without loading the entire user document.
Disadvantages of referencing
Referencing introduces additional application and query complexity.
- Related information may require multiple database operations.
- Aggregation queries may need
$lookupto combine related collections. - Mongoose applications may use
populate()to resolve references. - Updating or deleting related documents may require additional application logic.
- Operations spanning multiple documents do not automatically have single-document atomicity.
Referencing is useful when related data has an independent lifecycle, grows significantly, or is frequently accessed separately.
4. Embedding vs Referencing: Quick Comparison
| Factor | Embedding | Referencing |
|---|---|---|
| Storage | Same document | Separate documents |
| Read operations | Often fewer | May require additional queries |
| Document size | Can grow significantly | Easier to keep documents smaller |
| Data duplication | Possible | Usually reduced |
| Updates | Convenient within one document | Independent updates |
| Atomicity | Single-document atomicity | Multi-document atomicity requires additional mechanisms |
| Large relationships | Can become problematic | Generally more suitable |
| Independent access | Less convenient for large nested data | More convenient |
| Application complexity | Often simpler for related reads | Requires relationship resolution |
Neither approach is universally faster.
The best choice depends on your application's actual query patterns, document growth, update frequency, and consistency requirements.
5. Modeling One-to-One Relationships
A one-to-one relationship means one document is associated with exactly one other document.
For example:
- User and profile
- Employee and employee details
- Product and product specifications
Option A: Embed the related document
If the related information belongs to the parent entity and is usually accessed together, embedding is often a good choice.
{
_id: ObjectId("65f123456789abcdef123456"),
name: "Robin",
email: "[email protected]",
profile: {
bio: "Full Stack Developer",
location: "India",
experience: 2
}
}
This structure is convenient when the profile is an integral part of the user account.
Option B: Reference the related document
If the profile has its own lifecycle, is managed independently, or has separate access requirements, you can store it separately.
Users collection:
{
_id: ObjectId("65f123456789abcdef123456"),
name: "Robin",
email: "[email protected]",
profileId: ObjectId("65f987654321abcdef654321")
}
Profiles collection:
{
_id: ObjectId("65f987654321abcdef654321"),
bio: "Full Stack Developer",
location: "India",
experience: 2
}
The important consideration isn't simply that the relationship is one-to-one. It's how independently the related information needs to be managed.
Recommendation: Prefer embedding for small, closely related information. Use references when the related entity has a meaningful independent lifecycle or access pattern.
6. Modeling One-to-Many Relationships
A one-to-many relationship is one of the most common relationships in application development.
Examples include:
- A user has multiple addresses.
- A blog post has multiple comments.
- A customer has multiple orders.
- A category has multiple products.
The important question is whether the "many" side is bounded or can grow continuously.
Option A: Embed a bounded number of child documents
Consider a user with a small number of saved addresses.
{
_id: ObjectId("65f123456789abcdef123456"),
name: "Robin",
addresses: [
{
label: "Home",
city: "Thiruvananthapuram",
state: "Kerala",
country: "India"
},
{
label: "Office",
city: "Kochi",
state: "Kerala",
country: "India"
}
]
}
This is a good embedding candidate because the number of addresses is usually limited, and the application may retrieve them together with the user.
Option B: Reference a large or unbounded number of child documents
Now consider a blog post that can receive thousands of comments.
Embedding every comment inside the post document can eventually create a large document and make pagination difficult.
Instead, store comments separately.
Posts collection:
{
_id: ObjectId("65f111111111abcdef111111"),
title: "MongoDB Schema Design",
content: "Understanding data relationships..."
}
Comments collection:
{
_id: ObjectId("65f222222222abcdef222222"),
post: ObjectId("65f111111111abcdef111111"),
author: ObjectId("65f333333333abcdef333333"),
content: "Very useful explanation!",
createdAt: new Date()
}
Retrieve comments independently:
const comments = await Comment.find({
post: postId
})
.sort({ createdAt: -1 })
.limit(20);
This approach makes it easier to paginate, index, moderate, and manage comments independently.
Recommendation: Embed small, bounded child collections. Reference large or unbounded relationships that need independent querying and management.
7. Modeling Many-to-Many Relationships
A many-to-many relationship occurs when multiple documents can be associated with multiple other documents.
Examples include:
- Students enrolled in multiple courses.
- Products belonging to multiple categories.
- Users joining multiple groups.
- Employees working on multiple projects.
For example, a student can enroll in multiple courses, and each course can have multiple students.
Option A: Embed a small list of related information
If the relationship is small and the application primarily reads the information from one side, embedding selected related information can be useful.
{
_id: ObjectId("65f111111111abcdef111111"),
name: "MongoDB Fundamentals",
students: [
{
studentId: ObjectId("65f222222222abcdef222222"),
name: "Robin"
},
{
studentId: ObjectId("65f333333333abcdef333333"),
name: "Alex"
}
]
}
Notice that the embedded information contains only the fields required by the course view.
This is a form of denormalization. If the student's name changes, duplicated values may need to be updated.
Option B: Use references
When both sides have many relationships and need to be queried independently, references are generally more appropriate.
Students collection:
{
_id: ObjectId("65f222222222abcdef222222"),
name: "Robin"
}
Courses collection:
{
_id: ObjectId("65f111111111abcdef111111"),
name: "MongoDB Fundamentals"
}
Enrollments collection:
{
_id: ObjectId("65f444444444abcdef444444"),
student: ObjectId("65f222222222abcdef222222"),
course: ObjectId("65f111111111abcdef111111"),
enrolledAt: new Date(),
status: "active"
}
An independent enrollments collection is useful because the relationship itself can contain additional information, such as enrollment date, payment status, grades, or completion status.
You can also prevent duplicate enrollments using a compound unique index:
db.enrollments.createIndex(
{ student: 1, course: 1 },
{ unique: true }
);
This enforces uniqueness for each student-course pair.
Recommendation: For complex many-to-many relationships, use references or a dedicated relationship collection. Embedding can still be appropriate for small, bounded relationships where one-sided access is dominant.
8. Understanding Document Growth and the 16 MiB Limit
One of the most important considerations when embedding data is document growth.
MongoDB has a maximum BSON document size of 16 MiB.
That means a document containing a large embedded array cannot grow indefinitely.
Consider this structure:
{
_id: ObjectId("65f111111111abcdef111111"),
title: "My Blog Post",
comments: [
// Thousands of comments
]
}
If comments continue to accumulate, the document becomes increasingly large.
Even before reaching the 16 MiB limit, large documents can cause problems:
- More data may be transferred when only a few fields are needed.
- The working set may consume more memory.
- Frequently accessed data can become mixed with information that is rarely needed.
- Updating and managing large arrays becomes more complicated.
How to avoid unbounded arrays
Instead of embedding every comment, create a separate comments collection.
You can still maintain a small summary inside the post document:
{
_id: ObjectId("65f111111111abcdef111111"),
title: "My Blog Post",
commentCount: 1250,
latestComment: {
author: "Robin",
text: "Great article!"
}
}
The full comments remain in their own collection.
This gives the application quick access to summary information without loading the entire comment history.
For some workloads, MongoDB's subset and other data-modeling patterns can help balance frequently accessed information with large related datasets.
Official reference: MongoDB Document Size Limitations.
9. Data Duplication and Consistency
Embedding can introduce data duplication, especially when the same information is stored in multiple documents.
Consider an e-commerce application where multiple orders contain product information.
One approach is to store only the product reference:
{
_id: ObjectId("65f111111111abcdef111111"),
customer: ObjectId("65f222222222abcdef222222"),
items: [
{
product: ObjectId("65f333333333abcdef333333"),
quantity: 2
}
]
}
However, displaying the order may require retrieving the product's current name and price.
There is a potential problem: product details can change after an order is placed.
For historical order records, you usually want to preserve the information that existed when the customer made the purchase.
A practical approach is to store a snapshot of relevant product information in the order.
{
_id: ObjectId("65f111111111abcdef111111"),
customer: ObjectId("65f222222222abcdef222222"),
items: [
{
product: ObjectId("65f333333333abcdef333333"),
name: "Wireless Keyboard",
unitPrice: 1499,
quantity: 2
}
],
totalAmount: 2998
}
Here, the order contains both a product reference and a snapshot of the product's name and purchase price.
If the product's current price changes, the historical order remains unchanged.
This is intentional duplication.
When is duplication acceptable?
Duplication is useful when:
- The duplicated information is small.
- The data is frequently read together.
- Historical values must remain unchanged.
- Avoiding additional queries improves a common application workflow.
However, duplication becomes problematic when the same frequently changing information is copied into many documents and every copy must remain synchronized.
Important: Data duplication is not automatically bad in MongoDB. It is a deliberate schema design decision. The goal is to balance read efficiency, update complexity, and consistency requirements.
10. Using Mongoose to Work with References
In MERN applications, Mongoose is commonly used to define relationships between MongoDB documents.
Consider a blog application with separate User and Post models.
Define the User model
import mongoose from "mongoose";
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
}
});
export default mongoose.model("User", userSchema);
Define the Post model
import mongoose from "mongoose";
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
content: {
type: String,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
}
});
export default mongoose.model("Post", postSchema);
The ref option tells Mongoose which model is associated with the referenced ObjectId.
Retrieve a post with its author
You can use Mongoose's populate() method:
const post = await Post.findById(postId)
.populate("author", "name email");
The result includes the selected author fields instead of only the author ObjectId.
Retrieve posts belonging to a user
const posts = await Post.find({
author: userId
})
.select("title content createdAt")
.sort({ createdAt: -1 })
.limit(10);
You don't need to populate the author if the application already knows which user owns the posts.
Remember that populate() is a convenience for resolving references. It isn't the same as embedding, and it should not be used unnecessarily for every query.
For more techniques to optimize Mongoose queries, see Mongoose Performance Optimization: Practical Techniques for Node.js Applications.
11. Common MongoDB Schema Design Mistakes
Even experienced developers can make schema design decisions that become difficult to maintain as an application grows.
Here are some common mistakes worth avoiding.
1. Embedding unbounded arrays
Storing thousands of comments, notifications, messages, or activity records inside a single document can cause document growth problems.
Better approach: Store independently growing records in separate collections and reference their parent.
2. Referencing everything
Creating a separate collection for every small piece of information can introduce unnecessary queries and relationship resolution.
Better approach: Embed small information that belongs to a parent document and is commonly accessed together.
3. Duplicating frequently changing information without a strategy
Duplicating user names, product prices, or other mutable information across many documents can create consistency problems.
Better approach: Decide which fields are snapshots and which must always reflect the latest source value.
4. Designing schemas without considering queries
A technically valid schema isn't necessarily an efficient schema.
For example, a schema that requires several database operations for every frequently accessed page may not be ideal.
Better approach: Identify the application's most common read and write operations before choosing the relationship structure.
5. Using populate() for every relationship
Excessive population can make queries more complicated and increase database work.
Better approach: Select only the related information needed by the current operation. Consider embedding small, frequently accessed data where appropriate.
6. Ignoring document growth
A document that works well with ten embedded records might become problematic when it contains thousands.
Better approach: Estimate the expected growth of arrays and related data before deciding to embed them.
12. Production Best Practices for MongoDB Schema Design
Use these guidelines when designing schemas for real-world applications.
1. Design around application access patterns
Understand what your application reads and writes most frequently. Structure documents around those operations.
2. Prefer embedding for closely related, bounded data
If information belongs together and is commonly accessed together, embedding is often a good starting point.
3. Use references for independently managed entities
Large datasets, unbounded relationships, and independently queried entities are usually better candidates for references.
4. Avoid unbounded arrays
Always consider how embedded arrays will grow over time.
5. Use intentional denormalization
Duplicate small amounts of data when doing so improves common read operations or preserves historical information. Define how updates should be handled.
6. Keep documents focused
Don't store every related field in one document simply because MongoDB allows nested documents. Include the information that makes sense for that document's primary purpose.
7. Consider atomicity requirements
A single-document update is atomic. If an operation must update multiple documents consistently, evaluate whether a different schema design or a MongoDB transaction is appropriate.
8. Test your schema with realistic data
A schema that performs well with a small development dataset may behave differently with production-sized documents and relationships.
9. Measure before optimizing
Use query profiling and explain("executionStats") to understand actual query behavior. Don't assume embedding or referencing is faster without testing the relevant workload.
For more information about index selection and query execution, read MongoDB Indexing Explained: How Indexes Improve Query Performance.
13. A Practical Decision-Making Checklist
When deciding between embedding and referencing, ask these questions:
| Question | Suggested approach |
|---|---|
| Is the related information small and bounded? | Embedding |
| Is it frequently accessed together with its parent? | Embedding |
| Does it belong to the parent's lifecycle? | Embedding |
| Can the related array grow without a predictable limit? | Referencing |
| Does the related entity need independent queries? | Referencing |
| Is the same information shared by many documents? | Usually referencing |
| Does the relationship contain independent business data? | Usually referencing |
| Must a historical snapshot remain unchanged? | Embed a snapshot |
| Is the relationship complex and many-to-many? | Usually referencing |
These are guidelines, not strict rules. A combination of embedding and referencing is often the most practical solution.
Conclusion
Choosing between embedding and referencing is one of the most important parts of MongoDB schema design.
Embedding keeps related information together, simplifies common reads, and supports atomic updates within a single document. Referencing separates independently managed information, handles large relationships, and reduces unnecessary duplication.
For most applications, you don't need to choose only one approach. A well-designed MongoDB database often combines both.
The key is to understand how your application accesses its data, estimate how that data will grow, and design your documents around real application requirements rather than copying relational database structures directly.
Remember: Don't embed everything, and don't reference everything. Choose the structure that best supports your application's access patterns, consistency requirements, and expected growth.



