Data Modeling — Embedding vs. Referencing
MongoDB Performance Best Practices: Data Modeling — Embedding vs. Referencing
Introduction
Performance is one of the most important considerations when designing a MongoDB database. As applications grow, the way data is structured can significantly affect query response times, application performance, storage efficiency, and scalability.
Unlike traditional relational databases, which commonly organize data into tables connected through primary and foreign keys, MongoDB stores data in flexible, JSON-like BSON documents. This document-oriented approach gives developers the freedom to organize related information in ways that match application access patterns.
One of the most important decisions in MongoDB data modeling is choosing between embedding and referencing.
- Embedding stores related data inside the same document.
- Referencing stores related data in separate documents and connects them using identifiers.
Both approaches have advantages and limitations. Embedding can reduce the number of database queries required to retrieve related information, while referencing can reduce duplication and make independently managed data easier to maintain.
The best approach depends on how the application reads, updates, and manages its data. In this guide, we will explore MongoDB data modeling best practices, compare embedding and referencing, examine practical examples, and learn how to make performance-focused design decisions.
1. Understanding MongoDB Data Modeling
Data modeling is the process of deciding how information should be organized, stored, and connected within a database.
In MongoDB, data modeling involves determining:
- Which fields belong in the same document.
- Which relationships should be represented through embedded documents.
- Which relationships should use references.
- How frequently related information is accessed together.
- How large documents can become over time.
- How data duplication and consistency should be managed.
- Which indexes are needed to support common queries.
A well-designed data model reduces unnecessary database operations and makes queries easier to optimize.
Example: An e-commerce application
Consider an online shopping application that stores customer information and orders.
A customer document might contain:
{
"_id": 101,
"name": "Rahul Sharma",
"email": "[email protected]"
}
An order might contain:
{
"_id": 5001,
"customerId": 101,
"orderDate": "2026-10-20",
"totalAmount": 2500
}
In this example, the order refers to the customer through customerId. This is a referencing approach.
Alternatively, an order could embed a snapshot of the customer’s relevant details:
{
"_id": 5001,
"customer": {
"customerId": 101,
"name": "Rahul Sharma",
"email": "[email protected]"
},
"orderDate": "2026-10-20",
"totalAmount": 2500
}
This embedded structure makes it possible to retrieve the order and customer details with a single document read.
Notice that the two models represent the relationship differently. Neither is automatically better; the correct choice depends on the application’s requirements.
2. What Is Embedding in MongoDB?
Embedding is a data modeling technique in which related information is stored as nested documents or arrays inside a parent document.
Instead of retrieving multiple documents separately, an application can retrieve a parent document containing the information it needs.
Example: Embedding order items
Consider an order containing multiple products. An embedded order document could look like this:
{
"_id": 5001,
"customerName": "Rahul Sharma",
"orderDate": "2026-10-20",
"status": "Processing",
"items": [
{
"productId": 201,
"productName": "Keyboard",
"quantity": 1,
"price": 1200
},
{
"productId": 202,
"productName": "Mouse",
"quantity": 2,
"price": 650
}
],
"totalAmount": 2500
}
Here, the order and its line items are stored in a single document.
To retrieve the order with its items, the application can execute:
db.orders.findOne({ _id: 5001 });
MongoDB returns the order and its embedded items together.
Advantages of embedding
1. Faster retrieval for related data
When an application frequently reads an order and all its items together, embedding avoids additional queries to retrieve those items.
2. Fewer database round trips
The application can retrieve related information with one document read instead of issuing separate reads for each related collection.
3. Atomic updates within a document
MongoDB guarantees atomicity for a single-document write. Updating an order and its embedded items in one operation therefore provides single-document atomicity.
4. Simpler application logic
The application can work with a complete document rather than manually combining results from multiple collections for common operations.
5. Efficient indexing of nested fields
MongoDB supports indexes on embedded fields and array contents, including multikey indexes where appropriate.
For example:
db.orders.createIndex({ "items.productId": 1 });
This index can help queries that search orders by an embedded product identifier.
Limitations of embedding
Embedding is not always the best option.
- Documents can grow substantially as arrays accumulate more elements.
- Repeated information may increase storage requirements.
- Updating duplicated data across many documents can be difficult.
- Large, unbounded arrays can increase memory and index maintenance costs.
- Frequently changing shared information can require updates to multiple parent documents.
MongoDB documents have a maximum BSON document size of 16 MiB. A design that allows embedded arrays to grow without limits risks reaching this limit.
When should you use embedding?
Embedding is generally a strong choice when:
- Related information is frequently retrieved together.
- The embedded data belongs naturally to its parent.
- The relationship is one-to-one or one-to-few.
- The embedded array has a predictable size.
- The information is read frequently but changes relatively infrequently.
- The application benefits from atomic updates within a single document.
Examples include a user’s contact details, an order’s line items, a product’s fixed specifications, and a blog post’s small set of metadata.
3. What Is Referencing in MongoDB?
Referencing stores related information in separate documents and connects those documents through identifiers.
Instead of placing all related information inside a parent document, MongoDB stores each entity separately. The application can retrieve the related documents through additional queries or an aggregation using $lookup.
Example: Referencing products and orders
Suppose an application maintains a product catalog and allows products to appear in many different orders.
The products collection could contain:
{
"_id": 201,
"name": "Keyboard",
"price": 1200,
"category": "Accessories"
}
An order could store product references:
{
"_id": 5001,
"customerId": 101,
"orderDate": "2026-10-20",
"items": [
{
"productId": 201,
"quantity": 1
},
{
"productId": 202,
"quantity": 2
}
]
}
The order contains product identifiers rather than duplicating the entire product catalog record.
To retrieve the product associated with an order item, the application can issue another query:
db.products.findOne({ _id: 201 });
For a complete order containing several products, the application may retrieve the order first and then fetch the relevant product documents, or use an aggregation pipeline with $lookup.
Advantages of referencing
1. Reduced duplication
Product information can be maintained in one central document rather than copied into every order that uses the product.
2. Easier maintenance of shared data
If a product description or category changes, the application can update the central product record instead of updating every document that duplicates those fields.
3. Better support for large relationships
Referencing is useful when a parent is associated with many related documents, particularly when the relationship can grow indefinitely.
4. Independent document management
Related entities can be queried, updated, indexed, and managed independently.
5. More flexible relationships
Referencing works well for many-to-many relationships and for entities shared across many parents.
Limitations of referencing
Referencing also introduces trade-offs.
- Retrieving related data may require additional queries.
- Multiple database round trips can increase latency.
- Application code may need to combine results from different collections.
- Aggregation pipelines using
$lookupcan add processing overhead. - Multiple-document updates are not automatically atomic as a group.
MongoDB supports multi-document transactions when atomicity across several documents or collections is necessary, but transactions introduce additional operational complexity and should not replace good data modeling.
When should you use referencing?
Referencing is generally a good choice when:
- Related data is large or unbounded.
- Many documents share the same entity.
- Related information changes independently.
- The application often queries related entities separately.
- Data duplication would be expensive or difficult to maintain.
- Relationships are complex or many-to-many.
Examples include users and their many orders, products and suppliers, employees and departments, and social media users and their followers.
4. Embedding vs. Referencing: Key Differences
The following table summarizes the main trade-offs.
| Feature | Embedding | Referencing |
|---|---|---|
| Data storage | Related data is stored in one document | Related data is stored in separate documents |
| Read performance | Often better when related data is read together | May require extra queries or $lookup |
| Write complexity | Can simplify updates within one document | Can simplify independent entity updates |
| Data duplication | May increase duplication | Usually reduces duplication |
| Data consistency | Convenient for single-document atomic updates | Cross-document consistency may require coordination |
| Document size | Can grow with embedded data | Keeps individual documents more bounded |
| Relationship type | Best for bounded, closely related data | Best for shared, complex, or unbounded relationships |
| Application complexity | Often simpler for common reads | May require joins or additional queries |
| Scalability considerations | Watch document growth and write contention | Watch query count, join costs, and indexing |
Important: Embedding does not guarantee faster performance in every situation, and referencing does not necessarily mean a slow application. The actual outcome depends on document size, query patterns, indexes, data distribution, and workload.
5. How to Choose Between Embedding and Referencing
The most effective way to design MongoDB schemas is to start with application access patterns rather than copying a relational database design directly into MongoDB.
Step 1: Identify the most common queries
Ask how the application accesses its data.
For example, an e-commerce application may frequently need to:
- Retrieve an order with all its items.
- Display a product catalog.
- Find all orders placed by a customer.
- Update inventory after a purchase.
- Generate reports based on product categories.
If related information is almost always retrieved together, embedding may simplify the read path. If entities are frequently queried independently, referencing may be more appropriate.
Step 2: Understand relationship cardinality
Determine whether the relationship is one-to-one, one-to-few, one-to-many, or many-to-many.
- One-to-one: Embedding is often appropriate when the data belongs together.
- One-to-few: Embedding is often a good fit for small, bounded groups of related records.
- One-to-many: Either approach may work, depending on whether the number of related records is bounded and how the data is accessed.
- Many-to-many: Referencing is often preferable because each entity may be shared by multiple other entities.
For example, a user with a few notification preferences may be modeled with embedding. A user with millions of historical events should not have every event embedded in one document.
Step 3: Evaluate document growth
Ask whether the embedded information can grow indefinitely.
A product with a fixed set of specifications is unlikely to cause document growth problems. A popular social media post with millions of comments is a different case.
Unbounded arrays should generally be avoided. Consider separate collections, pagination, or bucket-based patterns when the relationship can grow continuously.
Step 4: Consider update frequency
Consider whether the related information changes independently.
For example, an order may need to retain the product name and price that applied at the time of purchase. Embedding a snapshot of those fields is often appropriate because historical order details should not automatically change when the product catalog changes.
By contrast, a current product description may be better maintained in the central products collection.
This leads to a useful distinction: duplicate data intentionally when it represents a historical snapshot or improves a frequently used read path, but avoid duplication that creates unnecessary synchronization work.
Step 5: Evaluate consistency requirements
If a business operation must update multiple documents together, determine whether single-document atomicity is sufficient or whether a multi-document transaction is required.
Embedding closely related data can simplify operations that need to change together. Referencing provides independent management but may require transactions or application-level coordination for cross-document consistency.
Step 6: Test with realistic workloads
Do not choose a model based only on assumptions.
Test the design using representative document sizes, data volumes, query frequency, concurrency, and write patterns. Measure query latency, documents examined, keys examined, throughput, and resource consumption before making final decisions.
6. Real-World Examples of Data Modeling
Different applications have different access patterns. The following examples demonstrate how to apply embedding and referencing decisions.
Example 1: E-commerce orders
An order typically contains a limited number of line items that are retrieved with the order.
A practical design is to embed the line items inside the order document:
{
"_id": 5001,
"customerId": 101,
"items": [
{
"productId": 201,
"productName": "Keyboard",
"unitPrice": 1200,
"quantity": 1
}
],
"status": "Confirmed"
}
Recommendation: Embed the order items and retain only the necessary product identifiers and historical purchase details. Keep the main product catalog separate when products are shared across orders.
This hybrid design reduces the need to retrieve additional documents to display an order while avoiding duplication of the entire product catalog.
Example 2: Blog posts and comments
A blog post may initially have only a few comments, but a popular post can accumulate thousands or millions.
Embedding all comments in one document creates unbounded growth and can make individual updates increasingly expensive.
A separate comments collection is often a better choice:
{
"_id": 9001,
"postId": 3001,
"authorId": 101,
"comment": "Very useful article!",
"createdAt": "2026-10-20T10:30:00Z"
}
The application can retrieve comments for a post with:
db.comments.find({ postId: 3001 })
.sort({ createdAt: -1 })
.limit(20);
A supporting index can improve this query:
db.comments.createIndex({
postId: 1,
createdAt: -1
});
Recommendation: Reference comments in a separate collection when their number can grow substantially. Embedding a small, bounded preview of recent comments can still be useful if the application’s main screen frequently displays it.
Example 3: User profiles and settings
A user’s profile and a small set of preferences are often retrieved together.
An embedded design may look like this:
{
"_id": 101,
"name": "Rahul Sharma",
"email": "[email protected]",
"preferences": {
"theme": "dark",
"language": "en",
"notifications": true
}
}
Recommendation: Embed small, closely related settings that are typically read and updated with the user profile. Store large activity histories, audit records, and other unbounded data separately.
Example 4: Social media followers
A social media user may have thousands or millions of followers. Storing every follower identifier in a single embedded array can create document growth and update-contention issues.
A separate relationship collection can represent the connection:
{
"_id": 7001,
"followerId": 101,
"followedUserId": 202,
"createdAt": "2026-10-20T10:30:00Z"
}
For a large system, the design should also consider indexes, pagination, uniqueness constraints, and high-volume write patterns.
Recommendation: Use references for large follower relationships rather than maintaining an unbounded array in each user document.
7. Hybrid Data Modeling: Combining Embedding and Referencing
In real-world MongoDB applications, developers do not always need to choose exclusively between embedding and referencing. A hybrid approach often provides the best balance of read performance, storage efficiency, and data consistency.
Consider an order management system that stores product information separately but embeds the details needed to process and display each order.
The products collection:
{
"_id": 201,
"name": "Keyboard",
"currentPrice": 1400,
"category": "Accessories"
}
The orders collection:
{
"_id": 5001,
"customerId": 101,
"items": [
{
"productId": 201,
"productName": "Keyboard",
"purchasePrice": 1200,
"quantity": 1
}
],
"status": "Delivered"
}
Notice that the order contains both a reference (productId) and embedded values (productName and purchasePrice).
The product’s current price is ₹1,400, while the recorded purchase price is ₹1,200. This difference is intentional: an order should preserve the price agreed upon when the purchase occurred.
The application can retrieve historical order information without looking up every product. When it needs the current product price or category, it can query the products collection.
Benefits of hybrid modeling
- Improves read performance for frequently accessed information.
- Preserves historical values where required.
- Reduces unnecessary duplication of large documents.
- Keeps frequently changing shared information in a central location.
- Supports different query patterns without forcing every relationship into one structure.
Hybrid modeling is particularly useful for e-commerce, financial applications, inventory systems, and other applications where historical records must remain stable while current entity information changes.
8. MongoDB Indexing Best Practices for Embedded and Referenced Data
Data modeling and indexing work together. Even a well-designed schema can perform poorly when frequently used queries lack suitable indexes.
8.1 Index fields used in common queries
Suppose an application frequently retrieves orders by customer ID.
db.orders.createIndex({ customerId: 1 });
This index can improve queries such as:
db.orders.find({ customerId: 101 });
Without a suitable index, MongoDB may need to examine many documents to identify matching orders.
8.2 Create indexes on embedded fields
MongoDB supports indexes on nested document fields.
For example:
db.orders.createIndex({ "items.productId": 1 });
This can support queries that search for orders containing a particular product:
db.orders.find({
"items.productId": 201
});
When indexing array fields, MongoDB generally creates a multikey index. Review the query patterns and index behavior before adding indexes to large arrays.
8.3 Index referenced fields in related collections
Suppose comments are stored separately from blog posts.
db.comments.createIndex({
postId: 1,
createdAt: -1
});
This compound index can support filtering comments by postId and retrieving recent comments in descending timestamp order.
Compound index field order matters. Design the index around the application’s actual filter, sort, and range conditions.
8.4 Avoid unnecessary indexes
Every additional index consumes storage and adds maintenance overhead when documents are inserted, updated, or deleted.
Create indexes to support demonstrated query requirements rather than indexing every field.
Use query profiling and execution statistics to identify useful indexes and remove redundant ones when appropriate.
9. Measuring Query Performance with explain()
MongoDB provides the explain() method to help developers understand how queries execute.
For example:
db.orders.find({
customerId: 101
}).explain("executionStats");
The output includes execution information such as:
executionTimeMillis: the reported execution time for the operation.totalDocsExamined: the number of documents examined.totalKeysExamined: the number of index keys examined.nReturned: the number of documents returned.winningPlan: the selected query execution plan.
These metrics help identify queries that examine many documents but return only a few results.
For example, if a query examines 100,000 documents and returns only 10, it may benefit from a suitable index or a different query strategy. However, a high examined-to-returned ratio is a diagnostic clue, not proof of a problem in every workload.
Comparing embedding and referencing
When evaluating two schema designs, run representative queries against both implementations.
Measure:
- Response time under realistic conditions.
- The number of database operations needed.
- Documents and index keys examined.
- CPU, memory, and storage consumption.
- Write throughput and update contention.
- Performance as the dataset grows.
A referenced model may require an extra query, but the additional work could be inexpensive if the related dataset is small and well indexed. An embedded model may reduce round trips but perform poorly if it requires loading large documents that the application rarely uses in full.
The goal is to optimize the complete workload, not just a single query.
10. Common MongoDB Data Modeling Mistakes
Understanding common mistakes helps prevent performance problems before they appear in production.
Mistake 1: Embedding everything
Placing every related entity inside one document may seem convenient, but it can lead to excessive document sizes, duplication, and update contention.
Best practice: Embed only related data that benefits from being stored together. Use references for independently managed or unbounded relationships.
Mistake 2: Referencing every relationship
Treating MongoDB exactly like a normalized relational database can create unnecessary query operations.
For example, retrieving a customer profile, preferences, address, and frequently displayed settings from multiple collections may introduce avoidable application complexity.
Best practice: Embed small, frequently accessed data when the relationship and consistency requirements make it appropriate.
Mistake 3: Creating unbounded arrays
A document containing an ever-growing list of events, messages, or followers can become difficult to update and may eventually exceed MongoDB’s 16 MiB document limit.
Best practice: Store high-volume child records separately. Consider pagination, subset patterns, or bucket patterns where suitable.
Mistake 4: Duplicating frequently changing data without a plan
Embedding shared information across many documents can create consistency issues if each copy must remain synchronized.
Best practice: Decide which fields are authoritative, which values are snapshots, and how duplicated data should be refreshed.
Mistake 5: Ignoring real query patterns
A schema designed without understanding application access patterns may perform poorly even if its structure looks logically correct.
Best practice: Identify the most frequent and expensive queries before finalizing the schema.
Mistake 6: Using $lookup without examining its cost
The $lookup stage is useful for joining documents across collections, but large joins, poor filtering, and missing indexes can increase resource consumption.
Best practice: Filter early where possible, index the relevant fields, and evaluate the aggregation using explain() and representative data.
Mistake 7: Over-indexing embedded arrays
Indexes on large arrays can increase index size and write overhead.
Best practice: Create indexes that support important queries and verify that their benefits justify their maintenance costs.
11. Advanced Data Modeling Patterns for Better Performance
MongoDB offers several modeling patterns that help developers manage common performance challenges.
11.1 Subset pattern
The subset pattern stores frequently accessed information in a parent document while keeping the complete dataset in a separate collection.
For example, a product may embed its five most recent reviews while storing all reviews in a separate collection.
This allows the application to display a product page quickly without loading thousands of reviews.
11.2 Bucket pattern
The bucket pattern groups related records into bounded documents.
For example, a system that records sensor readings might store a fixed time window of measurements in each bucket rather than creating an indefinitely growing array.
This approach can reduce document overhead and improve access to grouped data when the query patterns align with the bucket structure.
11.3 Computed pattern
The computed pattern stores frequently needed calculated values instead of recalculating them for every request.
For example, an application may maintain a product’s review count or average rating.
This can improve read performance, but the application must account for the cost and consistency of updating the computed values.
11.4 Extended reference pattern
The extended reference pattern copies selected fields from a referenced document into another document.
For example, an order might store the customer’s identifier and display name without duplicating the customer’s entire profile.
This can reduce the need for additional reads while keeping the copied information limited to the fields that matter.
These patterns can be combined with embedding and referencing to create a schema that reflects real application needs.
12. A Practical Decision Framework
Use the following guidelines when designing a new MongoDB collection.
| Question | Suggested direction |
|---|---|
| Is related data almost always read together? | Consider embedding |
| Is the related data small and bounded? | Consider embedding |
| Is the information a historical snapshot? | Consider embedding the required snapshot fields |
| Is the related entity shared by many parent documents? | Consider referencing |
| Can the child collection grow indefinitely? | Prefer separate documents |
| Does the related information change independently? | Consider referencing |
| Is the relationship many-to-many? | Usually consider referencing |
| Are reads and updates split across different access patterns? | Consider a hybrid model |
These are starting points rather than strict rules. Business requirements, consistency guarantees, document growth, and measured performance should determine the final design.
13. Implementation Checklist for MongoDB Performance
Before deploying a data model, review the following checklist.
-
Identify the application’s most common read and write operations.
-
Choose embedding, referencing, or a hybrid approach based on access patterns.
-
Check whether embedded arrays have a predictable upper bound.
-
Keep document sizes comfortably below MongoDB’s 16 MiB limit.
-
Define how duplicated fields will be synchronized or preserved as snapshots.
-
Create indexes for frequently executed queries.
-
Avoid unnecessary indexes and large, inefficient documents.
-
Evaluate transaction requirements for operations involving multiple documents.
-
Test query execution using
explain("executionStats"). -
Benchmark performance with realistic data volumes and concurrent workloads.
-
Reassess the schema as application requirements and data volumes evolve.
Conclusion
MongoDB data modeling is not simply about deciding where to store information. It is about structuring documents and relationships to support efficient reads, predictable writes, reliable consistency, and future growth.
Embedding is particularly useful when related information is small, bounded, and frequently accessed together. It can reduce database round trips and support atomic updates within a document.
Referencing is often better when data is shared across multiple entities, changes independently, or can grow without limits. It reduces duplication and allows related records to be managed separately, although retrieving them together may require additional queries or aggregation stages.
In many production systems, a hybrid approach offers the best balance. By embedding frequently accessed fields, referencing independently managed entities, creating appropriate indexes, and measuring actual query performance, developers can build MongoDB schemas that remain efficient as applications scale.
The most important principle is simple: Design your MongoDB schema around how your application uses its data, not just how the data is related.
A thoughtful data model established early can reduce unnecessary queries, simplify application logic, and help prevent performance bottlenecks as the database grows.
Frequently Asked Questions (FAQs)
1. Which is faster in MongoDB: embedding or referencing?
Embedding is often faster when related information is retrieved together because it can avoid additional queries. Referencing may require extra reads or a $lookup operation. Actual performance depends on document size, indexes, query patterns, and workload.
2. Can embedding and referencing be used together?
Yes. A hybrid model can embed frequently accessed or historical fields while keeping shared entities in separate collections. This approach is common in e-commerce, order management, and other applications with different read and consistency requirements.
3. Does MongoDB support joins between collections?
Yes. MongoDB supports the $lookup aggregation stage for combining documents from different collections. Referenced documents can also be retrieved using separate application queries.
4. What is the maximum size of a MongoDB document?
The maximum BSON document size is 16 MiB. Applications should avoid designs that allow embedded arrays or nested documents to grow without bounds.
5. Should every MongoDB relationship use an ObjectId reference?
No. Relationships can be represented using embedded documents, identifiers, or a combination of both. Referencing is a modeling choice, not a requirement for every relationship.
6. How can I identify a poorly designed MongoDB schema?
Warning signs include unbounded arrays, excessive duplication, slow queries, large numbers of examined documents, unnecessary joins, frequent synchronization updates, and growing document sizes. Use query profiling, execution statistics, and realistic workload tests to identify the underlying causes.
7. Does embedding eliminate the need for indexes?
No. Embedded documents and arrays can still benefit from indexes on frequently queried fields. Index selection should reflect the application’s filters, sorting requirements, and actual query workload.
References and Further Reading
For additional technical details, consult the official MongoDB documentation:
- MongoDB Data Modeling
- Embedded Data Models
- Referenced Data Models
- MongoDB Indexes
- Analyze Query Performance
Learnomate Technologies — Learn database concepts through practical examples, performance-focused design, and real-world implementation.

