MongoDB - Database Links

As you can see from the previous chapter of MongoDB Relationships, to implement a normalized database structure in MongoDB, we use the concept of referenced relationships, also called manual references, in which we manually store the id of the referenced document within another document. However, in cases where the document contains references from different collections, we can use MongoDB DBRefs .
DBRefs vs Manual Links
As an example of a scenario where we will use DBRef instead of manual referencing, consider a database where we store different types of addresses (home, office, mail, etc.) in different collections (address_home, address_office, address_mailing, etc.) .). Now, when a custom collection document refers to an address, it must also specify which collection to look up based on the type of address. In such cases, when a document refers to documents from many collections, we must use DBRef.
Using DBRefs
There are three fields in DBRefs −
-
$ref − This field specifies the collection of the referenced document
-
$id − This field specifies the _id field of the referenced document
-
$db is an optional field and contains the name of the database where the referenced document resides
$ref − This field specifies the collection of the referenced document
$id − This field specifies the _id field of the referenced document
$db is an optional field and contains the name of the database where the referenced document resides
Consider an example of a custom document with a DBRef field address as shown in the code snippet −
{ "_id" : ObjectId ( "53402597d852426020000002" ), "address" : { "$ref" : "address_home" , "$id" : ObjectId ( "534009e4d852427820000002" ), "$db" : "tutorialspoint" }, "contact " : "987654321" , "dob" : "01-01-1991" , "name" : "Tom Benzamin" }
The DBRef address field here indicates that the specified address document is in the address_home collection of the tutorialspoint database and has the ID 534009e4d852427820000002.
The following code dynamically searches the collection specified by the $ref parameter ( address_home in our case ) for the document with the ID specified by the $id parameter in DBRef.
> var user = db . users . findOne ({ "name" : "Tom Benzamin" }) > var dbRef = user . address > db [ dbRef . $ref ]. findOne ({ "_id"
What's Your Reaction?






