MongoDB Relationships
MongoDB relationships represent the logical interconnections between multiple documents.
Relationships between documents can be established 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 users and user addresses.
A user can have multiple addresses, so it is a one-to-many relationship.
The following are user A simple document structure:
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"name": "Tom Hanks",
"contact": "987654321",
"dob": "01-01-1991"
}
The following are address A simple document structure:
{
"_id":ObjectId("52ffc4a5d85242602e000000"),
"building": "22 A, Indiana Apt",
"pincode": 123456,
"city": "Los Angeles",
"state": "California"
}
Embedded relationships
Using the embedded method, we can embed user addresses into the user's 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. You can query the user's address like this:
>db.users.findOne({"name":"Tom Benzamin"},{"address":1})
Note: in the above query db and users represents the database and collection.
The disadvantage of this data structure is that if users and user addresses keep increasing and the data volume keeps growing, it will affect read and write performance.
Referenced relationships
Referenced relationships are a commonly used method when designing databases. This method separates the user data document from the user address data document, and establishes the relationship through the document's id field.
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin",
"address_ids": [
ObjectId("52ffc4a5d85242602e000000"),
ObjectId("52ffc4a5d85242602e000001")
]
}
In the above example, the user document's address_ids field contains an array of ObjectIds of the user addresses.
We can read these user address ObjectIds to obtain the user's detailed address information.
This method requires two queries: the first queries the ObjectIds of the user addresses, and the second obtains the user's detailed address information through the queried ids.
>var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
>var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})