MongoDB database references
In the previous section we mentioned the relationship MongoDB MongoDB reference to standardize the data structure of the document.
MongoDB has two references:
- Reference manual (Manual References)
- DBRefs
DBRefs vs reference manual
Consider such a scenario, we have a different set (address_home, address_office, address_mailing, etc.) stored in a different address (address, office address, mailing address, etc.).
Thus, when we call different address, you need to specify a collection, a collection of documents from multiple referenced documents, we should use DBRefs.
Use DBRefs
DBRef forms:
{ $ref : , $id : , $db : }
Significance of three fields represented by:
- $ Ref: collection name
- $ Id: reference id
- $ Db: database name, optional parameters
The following example uses a user data document DBRef, field address:
{ "_id":ObjectId("53402597d852426020000002"), "address": { "$ref": "address_home", "$id": ObjectId("534009e4d852427820000002"), "$db": "w3cschoolcc"}, "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin" }
address DBRef field specifies the address referenced documents are under address_home collection w3cschoolcc database, id is 534009e4d852427820000002.
The following code, we have to find the collection at the specified address information user id specified by $ ref parameter (address_home set):
>var user = db.users.findOne({"name":"Tom Benzamin"}) >var dbRef = user.address >db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
The above examples returned address_home collection address data:
{ "_id" : ObjectId("534009e4d852427820000002"), "building" : "22 A, Indiana Apt", "pincode" : 123456, "city" : "Los Angeles", "state" : "California" }