MongoDB Relationship
MongoDB relationships represent the logical interconnectedness of multiple documents.
Links can be established between documents through embedding and referencing.
the relationships in MongoDB can be:
- 1:1 (1 to 1)
- 1:n (1 to many)
- N:1 (multi-pair 1)
- N /A (many-to-many)
A user can have multiple addresses, so it is a one-to-many relationship.
The following is a simple structure of the user document
Embedded relationships
Using the embedded method, we can embed the user address in the user's document:
"_id": ObjectId("52ffc33cd85242f436000001"),
"Contact": "987654321",
"DOB": "01-01-1991",
"Name": "Tom benzamin",
"Address": [
{
"Building": "A, Indiana Apt",
"Pincode": 123456,
"City": "Los Angeles",
"State": "California"
},
{
"Building": "A, Acropolis Apt",
"Pincode": 456789,
"City": "Chicago",
"State": "Illinois"
}]
}
The above data is stored in a single document, which makes it easier to obtain and maintain data. You can query the user's address in this way:
>db.users.findone({"Name": "Tom benzamin"}, {"Address": 1})
Note: The db and users in the query above represent databases and collections.
The disadvantage of this data structure is that if the user and user address is increasing, the amount of data becomes larger, which will affect the read and write performance.
Referential relationships
A reference relationship is a common method of designing a database, which separates user data documents from user address data documents and establishes relationships by referencing the ID fields of the document.
{
"_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's document contains an array of object IDs(ObjectId) for the user's address.
We can read the object ID(ObjectId) of these user addressesto get the detailed address information of the user.
This method requires two queries, the first query of the user address of the object ID(ObjectId), the second time through the ID of the query to Obtain the user's detailed address information.
>var result = Db.users.findOne({"Name": "Tom benzamin"}, {"Address_ids": 1})
>var addresses = Db.address.find({"_id": {"$in": Result["Address_ids"]}})
MongoDB 8 Relationship