Modeling Relationships
Modeling relationships between data in MongoDB
Modeling relationships between data in MongoDB involves deciding how to represent related data using documents and collections. Unlike relational databases, MongoDB does not enforce foreign keys and joins, so you need to choose between embedding and referencing to represent relationships.
Types of Relationships
There are three main types of relationships to consider:
- One-to-One: A single document is related to another single document.
- One-to-Many: A single document is related to multiple documents.
- Many-to-Many: Multiple documents are related to multiple documents.
One-to-One Relationship
In a one-to-one relationship, you can either embed the related data within the same document or reference it in a separate document.
One-to-One Example
// Embedding Example { "_id": ObjectId("507f191e810c19729de860ea"), "name": "John Doe", "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" } } // Referencing Example { "_id": ObjectId("507f191e810c19729de860ea"), "name": "John Doe", "addressId": ObjectId("507f191e810c19729de860eb") } { "_id": ObjectId("507f191e810c19729de860eb"), "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" }
One-to-Many Relationship
In a one-to-many relationship, embedding is suitable for small sub-documents, while referencing is better for larger or frequently accessed related documents.
One-to-Many Example
// Embedding Example { "_id": ObjectId("507f191e810c19729de860ea"), "name": "John Doe", "orders": [ { "orderId": 1, "product": "Product A", "quantity": 2 }, { "orderId": 2, "product": "Product B", "quantity": 1 } ] } // Referencing Example { "_id": ObjectId("507f191e810c19729de860ea"), "name": "John Doe" } { "_id": ObjectId("507f191e810c19729de860eb"), "customerId": ObjectId("507f191e810c19729de860ea"), "orderId": 1, "product": "Product A", "quantity": 2 }
Many-to-Many Relationship
In a many-to-many relationship, you typically use an intermediate collection to represent the relationship.
Many-to-Many Example
// User Document { "_id": ObjectId("507f191e810c19729de860ea"), "name": "John Doe" } // Group Document { "_id": ObjectId("507f191e810c19729de860eb"), "name": "Admins" } // Membership Document (Intermediate Collection) { "_id": ObjectId("507f191e810c19729de860ec"), "userId": ObjectId("507f191e810c19729de860ea"), "groupId": ObjectId("507f191e810c19729de860eb") }