多表关系

最后更新于:2022-04-02 03:59:49

[TOC] ## 概述 mongodb 的关系有 - 1:1 (1对1) - 1: N (1对多) - N: 1 (多对1) - N: N (多对多) ## 关系梳理 有两个实际 user ``` { "_id":ObjectId("52ffc33cd85242f436000001"), "name": "Tom Hanks", "contact": "987654321", "dob": "01-01-1991" } ``` address ``` { "_id":ObjectId("52ffc4a5d85242602e000000"), "building": "22 A, Indiana Apt", "pincode": 123456, "city": "Los Angeles", "state": "California" } ``` ### 嵌入式关系 把user,address 放入一个集合中 ``` { "_id":ObjectId("52ffc33cd85242f436000001"), "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin", "address": [ { "building": "22 A, Indiana Apt", "pincode": 123456, "city": "Los Angeles", "state": "California" }, { "building": "170 A, Acropolis Apt", "pincode": 456789, "city": "Chicago", "state": "Illinois" }] } ``` 查找语句 ``` db.users.findOne({"name":"Tom Benzamin"},{"address":1}) ``` 缺点: - 如果用户和用户地址在不断增加,数据量不断变大,会影响读写性能。 ### 引用式关系 ``` { "_id":ObjectId("52ffc33cd85242f436000001"), "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin", "address_ids": [ ObjectId("52ffc4a5d85242602e000000"), ObjectId("52ffc4a5d85242602e000001") ] } ``` 需要查询两次 ``` > var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1}) > var addresses = db.address.find({"_id":{"$in":result["address_ids"]}}) ```
';