What is Referenced Data Model in MongoDB
1. Definition
The Referenced Data Model in MongoDB is a way of storing related data in separate documents and linking them using references (usually via ObjectId). It is also called a normalized data model.
2. When to Use
- When data is large and complex
- When relationships are one-to-many or many-to-many
- When data needs to be updated frequently
- When avoiding data duplication is important
3. Where it is Used
- E-commerce apps (users, orders, products)
- Social media platforms
- Blog systems (users and posts)
- Applications with complex relationships
4. Why We Use It
- Avoids data duplication
- Improves data consistency
- Handles large datasets efficiently
- Better for frequently updated data
5. How It Works
- Stores related data in different collections
- Uses ObjectId to create references
- Data is linked instead of embedded
- Requires multiple queries or population
Basic Syntax
// User document
{
_id: ObjectId("user123"),
name: "Manaswini"
}
// Order document referencing user
{
product: "Laptop",
userId: ObjectId("user123")
}Real Example
// Users Collection
{
_id: ObjectId("u1"),
name: "Manaswini"
}
// Orders Collection
{
product: "Phone",
userId: ObjectId("u1")
}6. Explanation
- Data is stored in separate collections
- Documents are linked using ObjectId
- Reduces duplication of data
- Requires joining logic in application or using populate
7. Advantages
- No data duplication
- Better data consistency
- Efficient for large datasets
- Easier to update data
8. Disadvantages
- Requires multiple queries
- Slower read performance compared to embedded model
- More complex data fetching
Interview Points
- Referenced model = linked documents
- Uses ObjectId for relationships
- Avoids data duplication
- Best for complex relationships
- Opposite of embedded model