As visible in the final bankruptcy of MongoDB relationships, to enforce a normalized database shape in MongoDB, we use the idea of Referenced Relationships also called Manual References wherein we manually keep the referenced record's id inside other file. However, in cases wherein a record carries references from one-of-a-kind collections, we are able to use MongoDB DBRefs.
DBRefs vs Manual References
As an example situation, where we would use DBRefs in place of manual references, remember a database where we are storing extraordinary sorts of addresses (home, workplace, mailing, etc.) in specific collections (address_home, address_office, address_mailing, and so forth). Now, while a person collection's record references an deal with, it also wishes to specify which collection to check out based totally at the deal with kind. In such eventualities in which a file references documents from many collections, we ought to use DBRefs.
Using DBRefs
There are 3 fields in DBRefs −
- $ref − This subject specifies the gathering of the referenced file
- $id − This discipline specifies the _id discipline of the referenced document
- $db − This is an non-compulsory field and carries the call of the database in which the referenced report lies
Consider a pattern consumer report having DBRef field cope with as proven within the code snippet −
{
"_id":ObjectId("53402597d852426020000002"),
"address": {
"$ref": "address_home",
"$id": ObjectId("534009e4d852427820000002"),
"$db": "tutorialspoint"},
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin"
}
The address DBRef discipline right here specifies that the referenced address document lies in address_home series underneath tutorialspoint database and has an identity of 534009e4d852427820000002.
The following code dynamically appears within the collection detailed with the aid of $ref parameter (address_home in our case) for a report with identification as specific through $id parameter in DBRef.
>var user = db.users.findOne({"name":"Tom Benzamin"})
>var dbRef = user.address
>db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
The above code returns the subsequent deal with record present in address_home collection −
{
"_id" : ObjectId("534009e4d852427820000002"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456,
"city" : "Los Angeles",
"state" : "California"
}