In the previous section of the MongoDB relationship, we mentioned the reference to MongoDB to standardize the data structure document.
There are two types of MongoDB references:
Manual reference (Manual References)
DBRefs
3.32.1. DBRefs vs manual reference ¶
Consider a scenario where we store different addresses (address, office address, email address, etc.) in different collections (address_home, address_office, address_mailing, etc.).
In this way, when we call different addresses, we also need to specify a collection, a document references a document from multiple collections, we should use DBRefs.
3.32.2. Use DBRefs ¶
The form of DBRef:
{ $ref : , $id : , $db : }
The meanings of the three fields are:
$ref: collection name
$id: referenced id
$db: database name, optional parameter
DBRef and field address are used in the user data document in the following example:
{
"_id":ObjectId("53402597d852426020000002"),
"address": {
"$ref": "address_home",
"$id": ObjectId("534009e4d852427820000002"),
"$db": "runoob"},
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin"
}
address The DBRef field specifies that the referenced address document is the address_home collection under the runoob database, and id is 534009e4d852427820000002.
In the following code, we find the user address information for the specified id in the collection by specifying the $ref parameter (the address_home 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"
}