Mongodb Relationships
# MongoDB Relationships
MongoDB relationships represent the logical connections between multiple documents.
Documents can be connected through embedding and referencing.
Relationships in MongoDB can be:
* 1:1 (One-to-One)
* 1: N (One-to-Many)
* N: 1 (Many-to-One)
* N: N (Many-to-Many)
Next, let's consider the relationship between a user and their addresses.
A user can have multiple addresses, so it is a one-to-many relationship.
Here is a simple structure of the **user** document:
{ "_id":ObjectId("52ffc33cd85242f436000001"), "name": "Tom Hanks", "contact": "987654321", "dob": "01-01-1991"}
Here is a simple structure of the **address** document:
{ "_id":ObjectId("52ffc4a5d85242602e000000"), "building": "22 A, Indiana Apt", "pincode": 123456, "city": "Los Angeles", "state": "California"}
* * *
## Embedded Relationships
Using the embedded method, we can embed the user's addresses into the user document:
{ "_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" }]}
The above data is stored in a single document, making it relatively easy to retrieve and maintain the data. You can query the user's addresses like this:
>db.users.findOne({"name":"Tom Benzamin"},{"address":1})
Note: In the above query, **db** and **users** represent the database and collection.
The disadvantage of this data structure is that if the number of users and their addresses keeps increasing, the growing data volume will affect read and write performance.
## Referenced Relationships
Referenced relationships are a commonly used method in database design. This method separates the user data document and the user address data document, establishing a relationship by referencing the **id** field of the documents.
{ "_id":ObjectId("52ffc33cd85242f436000001"), "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin", "address_ids": [ ObjectId("52ffc4a5d85242602e000000"), ObjectId("52ffc4a5d85242602e000001") ]}
In the above example, the **address_ids** field of the user document contains an array of ObjectIds for the user's addresses.
We can read these ObjectIds to retrieve the detailed address information for the user.
This method requires two queries: the first query gets the ObjectIds of the user's addresses, and the second query uses these IDs to fetch the detailed address information.
>var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})>var addresses = db.address.find({"_id":{"$in":result}})
YouTip