The relationship of MongoDB represents the logical interrelation between multiple documents.
Relationships can be established between documents through embedding and references.
Relationships in MongoDB can be:
1:1 (1 to 1)
1: n (1 to many)
N: 1 (many to 1)
N: n (many to many)
Next let’s consider the relationship between the user and the user address.
A user can have multiple addresses, so it is an one-to-many relationship.
The following is user The simple structure of the document:
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"name": "Tom Hanks",
"contact": "987654321",
"dob": "01-01-1991"
}
The following is address The simple structure of the document:
{
"_id":ObjectId("52ffc4a5d85242602e000000"),
"building": "22 A, Indiana Apt",
"pincode": 123456,
"city": "Los Angeles",
"state": "California"
}
3.31.1. Embedded relationship ¶
Using the embedded method, we can embed the user’s address 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 saved in a single document, which can be easily obtained and maintained. 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 databases and collections.
The disadvantage of this data structure is that if the user and user address are increasing, the amount of data is getting larger and larger, which will affect the read and write performance. Referential relationship is a method often used when designing a database, which separates the user data document from the user address data document by referencing the id Field to establish a relationship. In the above example, the user document address_ids The field contains an array of objects id (ObjectId) of the user’s address. We can read the object id (ObjectId) of these user addresses to get the detailed address information of the user. This method requires two queries, the first query the object id (ObjectId) of the user address, and the second time the detailed address information of the user is obtained through the queried id.Citation relation ¶
{
"_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"]}})