public class TagProperty { private String type; private int count; }
@Document(collection = "tag") public class Tag extends BaseEntity { @Field("user_id") @Indexed private String userId; //key->標籤文本 value->標籤屬性 private Map<String, TagProperty> tags; }
效果:java
/* 1 */ { "_id" : ObjectId("581074c63145d5e8cc498db7"), "_class" : "nd.sdp.idea.modules.tag.entity.Tag", "user_id" : "214372", "tags" : { "設計技巧" : { "type" : "default", "count" : 1 }, "生活啓發" : { "type" : "default", "count" : 23 }, "隨筆" : { "type" : "user", "count" : 0 } }, "delete_flag" : false }
這種形式的嵌套適用於一對多的狀況,裏面是key-value的形式,也便於刪除和修改。再如:ide
@Document(collection = "locations") public class Location extends BaseEntity { @Field(value = "user_id") private String userId; private Set<String> locations; }
一對一的時候,也能夠這樣設計:lua
@Document(collection = "idea_logs") @CompoundIndexes( @CompoundIndex(name = "_ii_df_idx_", def = "{'ideaId':1, 'deleteFlag':1}") ) public class IdeaLog extends BaseEntity { @Field(value = "idea_id") private String ideaId; private String info; @Field(value = "create_at") private Long createAt; private Operator operator; @Field(value = "erp_order") private ErpOrder erpOrder; private String evaluation; }
public class Operator { @Field(value = "user_id") private String userId; @Field(value = "user_name") private String userName; }
但嵌套自己存在須要注意的問題,好比嵌套內容數據量的大小,對內嵌文檔的刪除、修改是否便利等等。idea
下面這種設計就不便於操做:spa
{ username: <用戶名>, password: <密碼>, tasks: [ { taskname: <任務名>, taskinfo: <任務描述> },{ taskname: <任務名>, taskinfo: <任務描述> }...... ] }
這是能夠修改成user和task2個文檔,task中包含user的id。設計