Data Modeling
Discount Schema Design Strategies
Effective data modeling for product discounts in MongoDB requires careful consideration of flexibility, performance, and scalability.
Discount Schema Patterns
1. Embedded Discount Document
{
"_id": ObjectId(),
"product_name": "Wireless Headphones",
"base_price": 199.99,
"discount": {
"type": "percentage",
"value": 0.15,
"start_date": ISODate("2023-07-01"),
"end_date": ISODate("2023-07-31"),
"conditions": {
"minimum_purchase": 100.00,
"customer_tier": "gold"
}
}
}
2. Separate Discount Collection
graph TD
A[Product Collection] -->|Reference| B[Discount Collection]
B --> C[Percentage Discounts]
B --> D[Fixed Amount Discounts]
B --> E[Promotional Discounts]
Discount Modeling Approaches
Approach |
Pros |
Cons |
Embedded Document |
Fast Queries |
Limited Complex Rules |
Separate Collection |
Flexible Rules |
Additional Joins |
Hybrid Approach |
Balanced Solution |
Moderate Complexity |
Index Optimization Strategies
// Compound Index for Efficient Discount Queries
db.products.createIndex({
"discount.type": 1,
"discount.start_date": -1,
"discount.end_date": -1
});
Advanced Modeling Considerations
Dynamic Discount Rules
- Support multiple discount types
- Implement conditional discounts
- Enable real-time price calculations
- Use sparse indexes
- Implement caching mechanisms
- Minimize document size
LabEx Recommended Approach
For most e-commerce applications, LabEx suggests a hybrid modeling approach that balances flexibility and query performance.
Sample Hybrid Schema
{
"_id": ObjectId(),
"product_id": "PROD-001",
"name": "Smart Watch",
"base_price": 249.99,
"discount_ref": ObjectId("discount_document_id"),
"dynamic_rules": [
{ "type": "volume_based", "threshold": 5 },
{ "type": "loyalty_discount" }
]
}
Key Takeaways
- Choose schema based on specific use case
- Prioritize query performance
- Design for future scalability
- Implement flexible discount logic