MongoDB数据建模实战
MongoDB数据建模实战
引言
MongoDB灵活的文档模型允许灵活的数据建模。本文介绍MongoDB数据建模的原则和最佳实践。
文档设计原则
1.1 嵌入 vs 引用
/** * 嵌入 vs 引用 */ public class DataModeling { /** * 嵌入文档(适合一对一关系) */ public Document embedDocument() { return new Document() .append("orderId", "order123") .append("customer", new Document() .append("name", "John") .append("email", "john@example.com")) .append("items", Arrays.asList( new Document("product", "Widget", "quantity", 2) )); } /** * 引用文档(适合多对多关系) */ public Document referenceDocument() { return new Document() .append("userId", "user123") .append("orderId", "order123"); } }总结
MongoDB数据建模需要根据业务场景选择合适的模式。
