MongoDB Relationship:
MongoDB relationships represent the logical interconnectedness of multiple documents. Links can be established between documents through embedding and referencing.
1. Embedding Relationship:
Form: Embed a document in another document.
Pros: Data is stored in a single document, which makes it easier to get and maintain data. (One-time query only)
Disadvantage: If the amount of data is constantly increasing, it will affect read and write performance.
Examples of Use:
{
"_id": ObjectId ("52ffc33cd85242f436000001"),
"Name": "Tom benzamin",
"Address": [
{
"Building": "A, Indiana Apt",
"Pincode": 123456,
},
{
"Building": "A, Acropolis Apt",
"Pincode": 456789,
}]
}
Query Example:
Db.users.findOne ({"Name": "Tom benzamin"},{"Address": 1})
2. Citation relationship:
Form: Establishes a relationship through the ID field of the document .
Cons: Queries are required two times.
Examples of Use:
{
"_id": ObjectId ("52ffc33cd85242f436000001"),
"Name": "Tom benzamin",
"Address_ids": [
ObjectId ("52ffc4a5d85242602e000000"),
ObjectId ("52ffc4a5d85242602e000001")
]
}
Query Example:
>var result = Db.users.findOne ({"Name": "Tom benzamin"},{"Address_ids": 1})
>var addresses = Db.address.find ({"_id": {"$in": result["Address_ids"]}})
Database reference: You should use DBRefswhen a document needs to refer to a document from multiple collections.
form of DBRefs:
{$ref:, $id:, $db:}
The three fields represent the meaning:
$ref: Collection name
$id: The ID of the reference
$DB: Database name, optional parameters
Examples of Use:
{
"_id": ObjectId ("53402597d852426020000002"),
"Address": {
"$ref": "Address_home",
"$id": ObjectId ("534009e4d852427820000002"),
"$db": "W3CSCHOOLCC"},
"Contact": "987654321",
"DOB": "01-01-1991",
"Name": "Tom benzamin"
}
Query Example:
>var user = Db.users.findOne ({"Name": "Tom Benzamin"})
>var Dbref = user.address
>db[dbref. $ref].findone ({"_id":(dbref. $id)})
MongoDB Relationships and database references