Mongodb Database References
# MongoDB Database References
In the previous chapter on MongoDB Relationships, we mentioned MongoDB references for standardizing document data structures.
There are two types of MongoDB references:
* Manual References
* DBRefs
* * *
## DBRefs vs Manual References
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.).
In this case, when we retrieve different addresses, we also need to specify the collection. When a document references documents from multiple collections, we should use DBRefs.
* * *
## Using DBRefs
The format of a DBRef is:
{ $ref : , $id : [, $db : ] }
The three fields represent:
* $ref: The collection name
* $id: The referenced id
* $db: The database name, an optional parameter
In the following example, a user data document uses a DBRef in the field "address":
{ "_id":ObjectId("53402597d852426020000002"), "address": { "$ref": "address_home", "$id": ObjectId("534009e4d852427820000002"), "$db": "tutorial"}, "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin"}
The **address** DBRef field specifies that the referenced address document is in the "address_home" collection of the "tutorial" database, with an id of "534009e4d852427820000002".
In the following code, we retrieve the user's address information from the specified 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 example returns the address data from the "address_home" collection:
{ "_id" : ObjectId("534009e4d852427820000002"), "building" : "22 A, Indiana Apt", "pincode" : 123456, "city" : "Los Angeles", "state" : "California"}
YouTip