Mongodb Relationships2
Mongodb Relationships2
Using DBRefs
There are three fields in DBRefs:
$id: This field specifies the _id field of the referenced document
$db: This is an optional field and contains name of the database in which the referenced
document lies
Consider a sample user document having DBRef field address as shown below:
{
"_id":ObjectId("53402597d852426020000002"),
"address": {
"$ref": "address_home",
"$id": ObjectId("534009e4d852427820000002"),
"$db": "tutorialspoint"},
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin"
}
The address DBRef field here specifies that the referenced address document lies in
address_home collection under tutorialspoint database and has an id of
534009e4d852427820000002.
The following code dynamically looks in the collection specified by $ref parameter
(address_home in our case) for a document with id as specified by $id parameter in DBRef.
The above code returns the following address document present in address_home collection:
{
"_id" : ObjectId("534009e4d852427820000002"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456,
"city" : "Los Angeles",
"state" : "California"
}
Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js