MongoDB Relationships - MongoDB

What are relationships in MongoDB?

Relationships in MongoDB show how different documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N.

For example, consider a case of storing addresses for users. One user can have multiple addresses making this a 1:N relationship.

Below is the sample document structure of user document

Below is a sample document structure of address document

Modeling Embedded Relationships

In the embedded approach, we will embed the address document inside the user document.

This approach will maintain all the related data in a single document, which makes it easy to retrieve and maintain. Whole document can be retrieved in a single query such as

Remember that in the above query, db and users are the database and collection respectively.

Drawback is that if the embedded document size grows too much, then it can impact the read/write performance.

Modeling Referenced Relationships

This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately, but the user document will contain a field which references the address document's id field.

As shown above, user document consists of array field address_ids which includes ObjectIds of corresponding addresses. Using these ObjectIds, address documents can be queried to get address details from there. You need two queries with this approach: one is to fetch the address_ids fields from user document and second is to fetch these addresses from address collection.

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

MongoDB Topics