mongodb 设计模式
一对多设计方案
一对很少
使用嵌套结构
eg: 一个人有多个联系地址 数十不过百
{ "name": "jeff", "addresses": [ {"street": "123", "city": "sz", "_id": "id1"}, {"street": "5th ", "city": "sh", "_id": "id2"} ] }
一对很多 数百不过千
eg: 一个产品由数百个零部件构成 使用间接引用,将零件的id作为数组存放在产品文档中
part
[ {"name": "1","_id": "id1"}, {"name": "1","_id": "id1"} ]
product
{ "name": "car", "parts" : [ "id1", "id2", "id3" ] }
一对非常多,成千数万
eg1: weibo 里面following 和 followers 可以达到数十万,数百万
使用数组可能会超过一个文档最大16M的限制
mongodb数组太大会验证影响性能
可以专门建立一个collection来描述关系用户1-N关注者
同时为了避免需要得到关注和粉丝数量的时候,不去count一次,在用户对象里面添加两个字段
一个是关注数,另一个是粉丝数,当变化时就更新一下
user
[ {"user": "kimi","follower_count": 2, "following_count": 0}, {"user": "tommon","follower_count": 0, "following_count": 2}, {"user": "tony", "follower_count": 1, "following_count": 0} ]
[ {"user": "kemi","follow": "tommon"}, {"user": "kemi","follow": "tommon"}, {"user": "tony","follow": "kemi"} ]
作者:不如做一只猫
链接:https://www.jianshu.com/p/e53c6ade7c27