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; }
效果:
/* 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的形式,也便于删除和修改。再如:
@Document(collection = "locations") public class Location extends BaseEntity { @Field(value = "user_id") private String userId; private Set<String> locations; }
一对一的时候,也可以这样设计:
@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; }
但嵌套本身存在需要注意的问题,比如嵌套内容数据量的大小,对内嵌文档的删除、修改是否便利等等。
下面这种设计就不便于操作:
{ username: <用户名>, password: <密码>, tasks: [ { taskname: <任务名>, taskinfo: <任务描述> },{ taskname: <任务名>, taskinfo: <任务描述> }...... ] }
这是可以修改为user和task2个文档,task中包含user的id。