MongoDB Relationship Example

MongoDB has relationships and this shows how different documents are related to each other logically. These relationship can be designed through referenced and embedded ways. These relationship can be one to one , one to many, many to one or many to many. Here we will give examples of MongoDB relationship.

Embedded Relationships

In the embedded methodology, we will embed the address document inside the client document.

This methodology keeps up all the related information in a single document which makes it simple to recover and keep up. The entire document could be recovered in a single query as mentioned below:

db.users.findone({"name":"mAnsari"},{"address":1})

In the referenced query listed above the db and clients are the database and collection separately.

The downside is that if the inserted document continues developing excessively in size, it can affect the read/write execution.

Referenced Relationships

This is the methodology of outlining standardized relationship. In this methodology, both the client and location documents will be kept up independently however the client document will contain a field that will reference the location document’s id field.

As demonstrated over, the client document contains the array field address_ids which has Objectids of relating addresses . With the help these Objectids, we can query the location documents and get address details from that point. With this methodology, we will require two query: first to bring the address_ids fields from client document and second to get these address from address collection.

As seen in the last part of MongoDB Relationships, to actualize a standardized database structure in MongoDB we utilize the idea of Referenced Relationships likewise alluded to as Manual References in which we physically store the referenced document’s id inside other document. Nonetheless, in situations where a document contains references from distinctive collections, we can utilize MongoDB DBRefs.

DBRefs vs Manual References

As a sample situation where we would utilize DBRefs rather than Manual References, consider a database where we are putting away diverse sorts of address (home, office, mailing, and so forth) in distinctive collection. Presently, when a client collection’s document references an address, it additionally needs to determine which collection to search according to the address . In such situations where a document references documents from numerous collection , we ought to utilize DBRefs.

Consider a specimen client document having Dbref field address as appeared: