Home >>MongoDB Tutorial >MongoDB Database References

MongoDB Database References

MongoDB Database References

As seen in the last chapter of MongoDB relationships, we use the idea of Referenced Relationships, often referred to as Manual References, to enforce a normalized database structure in MongoDB, in which we manually store the ID of the referenced document within another document. We may however, use MongoDB DBRefs in cases where a document includes references from various collections.

DBRefs vs Manual References

Consider a database where we store various types of addresses (home, office, mailing, etc.) in different collections (address home, address office, address mailing, etc.) as an example scenario in which we can use DBRefs instead of manual references. Now when the document from a user collection references an address, it often needs to define which collection to look at depending on the type of address. We can use DBRefs in such situations where a document references documents from several collections.

Using DBRefs

Using DBRefs

$ref − This field specifies the referenced document collection,

$id − This field defines the referenced document's _id field

$db − This field is optional and includes the database name in which the referenced document is located.

Consider a DBRef field address sample user document, as seen in the code snippet.

   "address": {
   "$ref": "address_home",
   "$id": ObjectId("534009e4d852427820000002"),
   "$db": "tutorialspoint"},
   "contact": "987654321",
   "dob": "01-07-1993",
   "name": "Tom Benzamin"

The DBRef address field here specifies that the referenced address document is stored under the tutorialspoint database in the address home collection and has an id of 534009e4d852427820000002.

In a list defined by the $ref parameter (address home in our case), the following code dynamically searches for a document with an id as specified by the $id parameter in the DBRef.

>var user = db.users.findOne({"name":"Tom Benzamin"})
>var dbRef = user.address

The above code returns the following address document present in address_home collection −

   "_id" : ObjectId("534009e4d852427820000002"),
   "building" : "57 C, Indiana Apt",
   "pincode" : 123456,
   "city" : "Los Angeles",
   "state" : "California"

No Sidebar ads