官术网_书友最值得收藏!

One-to-many, many-to-many

When the number of elements in the many side of the relationship can grow unbounded, it's better to use references.

References can come in two forms:

From the one-side of the relationship, store an array of many-sided-elements:

> db.Person.findOne()
{ "_id" : ObjectId("590a530e3e37d79acac26a41"), "name" : "alex", addresses:
[ ObjectID('590a56743e37d79acac26a44'),
ObjectID('590a56743e37d79acac26a46'),
ObjectID('590a56743e37d79acac26a54') ] }

This way we can get the array of addresses from the one-side and then query with in to get all the documents from the many-side:

> person = db.Person.findOne({"name":"mary"})
> addresses = db.Addresses.find({_id: {$in: person.addresses} })

Turning this one-many to many-many is as easy as storing this array in both ends of the relationship (person and address collections).

From the many-side of the relationship, store a reference to the one-side:

> db.Address.find()
{ "_id" : ObjectId("590a55863e37d79acac26a44"), "person": ObjectId("590a530e3e37d79acac26a41"), "address" : [ "N29DD" ] }
{ "_id" : ObjectId("590a55863e37d79acac26a46"), "person": ObjectId("590a530e3e37d79acac26a41"), "address" : [ "SW1E5ND" ] }
{ "_id" : ObjectId("590a55863e37d79acac26a54"), "person": ObjectId("590a530e3e37d79acac26a41"), "address" : [ "N225QG" ] }
> person = db.Person.findOne({"name":"alex"})
> addresses = db.Addresses.find({"person": person._id})

As we can see, with both designs we need to make two queries to the database to fetch the information. The second approach has the advantage that it won't let any document grow unbounded so it can be used in cases where one-many is one-millions.

主站蜘蛛池模板: 呼伦贝尔市| 固安县| 吉安县| 寻乌县| 昌图县| 泸水县| 阳西县| 穆棱市| 澄江县| 阳朔县| 当涂县| 青海省| 罗甸县| 鄂托克前旗| 历史| 武城县| 舒城县| 邹城市| 高陵县| 句容市| 邵阳市| 汪清县| 株洲市| 边坝县| 东乡族自治县| 南京市| 罗田县| 华蓥市| 青河县| 高雄县| 博客| 台南市| 正定县| 东乌珠穆沁旗| 武邑县| 辛集市| 阿克| 安多县| 淄博市| 含山县| 蒙城县|