MongoDB database reference
In the previous chapter MongoDB relationship we mentioned MongoDB references to standardize data structure documents.
There are two types of MongoDB references:
Manual References
DBRefs
DBRefs vs Manual Reference
Consider a scenario where we store different addresses (home address, office address, mailing address, etc.) in different collections (address_home, address_office, address_mailing, etc.) address, etc.).
In this way, we also need to specify the collection when calling different addresses. If a document refers to documents from multiple collections, we should use DBRefs.
Use DBRefs
The form of DBRef:
{ $ref : , $id : , $db : }
The meaning of the three fields is:
$ref : Collection name
$id: Referenced id
$db: Database name, optional parameters
In the following example, the user data document uses DBRef, and the field address is:
{ "_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 the w3cschoolcc database under the address_home collection, and the id is 534009e4d852427820000002.
In the following code, we specify the $ref parameter (address_home collection) to find the user address information of the specified id in the collection:
>var user = db.users.findOne({"name":"Tom Benzamin"}) >var dbRef = user.address >db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
The above example returns the address data in the address_home collection:
{ "_id" : ObjectId("534009e4d852427820000002"), "building" : "22 A, Indiana Apt", "pincode" : 123456, "city" : "Los Angeles", "state" : "California" }