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:
{$ref:, $id:, $db: }
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"), "$db": "W3CSCHOOLCC"}, "contact": "987654321", "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.users.findOne ({"Name": "Tom Benzamin"}) >var dbref = user.address>db[dbref. $ref].findone ({"_id" :(dbref. $id)})
The above instance returns the address data from the Address_home collection:
{ "_id": ObjectId ("534009e4d852427820000002"), "building": "A, Indiana Apt", "Pincode": 123456, ' city ': ' Los Angeles ', ' State ': ' California '}
MongoDB Database Reference