In the last chapter of MongoDB relationships, we used the concept of Referenced Relationships (also referred to as Manual References) to implement a normalized database structure in MongoDB, in which the referenced document's id is manually stored inside other document. If a document contains references from different collections, we can use MongoDB DBRefs.
For example, we can use DBRefs instead of manual references. Consider a database where we store different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc). Now, when a user collection's document references an address, it also has to specify which collection to look into based on the address type. In such scenarios where a document references documents from many collections, DBRefs should be used.
DBRefs has 3 fields
Consider a sample user document which has DBRef field address as shown in the code snippet
The address DBRef field here will specify that the referenced address document lies in address_home collection under wisdomjobs database and has an id of 534009e4d852427820000002.
Below 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.
Above code returns below address document present in address_home collection
MongoDB Related Interview Questions
|Python Interview Questions||C & Data Structures Interview Questions|
|Hadoop Interview Questions||Node.js Interview Questions|
|Scala Interview Questions||Socket Programming Interview Questions|
|HBase Interview Questions||Solaris Administrator Interview Questions|
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.