There are two types of MongoDB references:
- Manual reference (Manual References)
- DBRefs
DBRefs vs Manual Reference
Consider a scenario in which we store different addresses (address, Office address, email address, etc.) in different collections (Address_home, Address_office, address_mailing, etc.).
This way, when we call different addresses, we also need to specify the collection, a document that references the document from multiple collections, and we should use DBRefs.
Using DBRefs
form of Dbref:
{:,:,:}
The three fields represent the meaning:
- $ref: Collection Name
- $ID: The ID of the reference
- $DB: Database name, optional parameters
The user data document in the following example uses the Dbref, field address:
{ "_ID":ObjectId("53402597d852426020000002"), "Address": { "$ref": "Address_home", "$id" : Objectid "534009e4d852427820000002" span class= "str" > "$db" : "W3CSCHOOLCC" },< Span class= "PLN" > "contact" : "987654321" Span class= "pun" >, "DOB" : "01-01-1991" , "name" : "Tom benzamin" }
Address The Dbref field specifies that the referenced address document is a W3CSCHOOLCC database under the Address_home collection, with an ID of 534009e4d852427820000002.
In the following code, we look up the user address information for the specified ID in the collection by specifying the $REF parameter (Address_home collection):
>Var user = Db.. Findone ({ "name" : "Tom Benzamin" >var Dbref = User.>db[dbref $ref findone ({:( Dbref. $id
The above instance returns the address data from the Address_home collection:
{ "_ID" : objectid ( "534009e4d852427820000002" Span class= "pun"), "building" : "A, Indiana Apt" , "Pincode" : 123456, "city" : "Los Angeles" Span class= "pun" >, "state" : "California" }
MongoDB Database Reference