Embedded Document Example in Mongodb
Embedded Document Example in Mongodb
other documents. This approach is useful for data that is frequently accessed
together and has a clear hierarchical relationship. Here’s an example of an
embedded document model for an e-commerce application involving `Users`,
`Orders`, and `Products`.
### Explanation
- **Data Locality**: Since related data is stored together, read operations are faster
because all necessary data is in a single document.
- **Simplicity**: The data model is simpler and easier to understand as related data
is nested directly.
Here's how you might insert a user document with an embedded order using
MongoDB shell commands:
```javascript
db.users.insertOne({
"_id": ObjectId("60d5ecf7b2e24b3dc8c6123b"),
"name": "Alice Smith",
"email": "alice@example.com",
"address": "123 Maple Street",
"orders": [
{
"order_id": ObjectId("60d5ecf7b2e24b3dc8c6123e"),
"order_date": ISODate("2023-07-20T10:30:00Z"),
"status": "Shipped",
"products": [
{
"product_id": ObjectId("60d5ecf7b2e24b3dc8c6123c"),
"name": "Laptop",
"quantity": 1,
"price": 1200.00
},
{
"product_id": ObjectId("60d5ecf7b2e24b3dc8c6123d"),
"name": "Smartphone",
"quantity": 2,
"price": 800.00
}
],
"total": 2800.00
}
]
});
```
To retrieve a user with their embedded orders, you can use a simple `find` query:
```javascript
db.users.findOne({ _id: ObjectId("60d5ecf7b2e24b3dc8c6123b") });
```
This query will return the user document along with all embedded orders and
products.
### Considerations
- **Document Size**: MongoDB documents have a size limit of 16MB. Ensure that
the embedded documents do not cause the total document size to exceed this limit.
- **Data Duplication**: If the same embedded documents are used in multiple
places, consider the trade-offs between embedding and referencing to avoid
excessive data duplication.
- **Update Complexity**: Updating nested documents can be more complex and
may require using positional `$` operators or array filters.
Using embedded documents can greatly enhance performance and simplify your
data model for scenarios where data is closely related and frequently accessed
together.
db.users.insertOne({
"_id": 10010,
"name": "Alice Smith",
"email": "alice@example.com",
"addresses": {
"permanent": {
"street": "123 Maple Street",
"city": "Springfield",
"state": "IL",
"zip": "62701",
"country": "USA"
},
"contractual": {
"street": "456 Elm Street",
"city": "Shelbyville",
"state": "IL",
"zip": "62702",
"country": "USA"
}
}
});