MongoDB Database References - MongoDB

How references are used in MondoDB database?

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.

DBRefs vs Manual References

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.

Using DBRefs

DBRefs has 3 fields

  • $ref − $ref field specifies the collection of the referenced document
  • $id − $id field specifies the _id field of the referenced document
  • $db − $db is an optional field which contains the name of the database in which the referenced document lies

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

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

MongoDB Topics