📄 Embedded documents or relational collections in MongoDB 📦

📄 Embedded documents or relational collections in MongoDB 📦

In a relational database, you store each individual entity in its own table and link them together through foreign keys. 🗃️🔗 While MongoDB certainly supports references from one document to another, and even multi-document joins, it’s your choice to use a document database 📄🗄️ or a relational one.

For example, let’s look at a simple structure with a user 👤 and their addresses 🏠.

One way to structure the relationship between the two entities is to use references: 🔗

Another approach is to just embed the address 🏠 document in the user 👤 document, like so: 🔍📥

Why (and when) you should prefer embedding to referencing? 🤔

When related data is small 📏

When you have a small amount of related data, embedding is the more optimal choice. When data is expected to grow larger, separate collections make more sense. For example, a person can have 2 to 3 addresses so it can be embedded. In the case of product reviews, embedding them in a product collection would be an unwise decision, so store them in a separate collection. 🏡🗂️

How you are accessing data 📊

If you are displaying all related data, then use embedded documents. For example, when displaying a user profile, all addresses are displayed with user info. In the case of product reviews, usually most recent reviews are displayed, so relational records are a better option. 👀🗃️

Searching and Sorting data 🔍📑

Searching and sorting require frequent data access. When you have a use case where related records are not searched and accessed frequently, go for the embedded pattern. For frequent search and sorting, relational records will work best. For example, for product reviews, users want to search by keyword or sort the list by rating and date of reviews. 🧐🔎

Updating and Deleting data 🔄🗑️

Updating and deleting records in embedded documents requires special queries and slightly tricky work to do. In the case of related records, it is very easy to update or delete records in the collection. 🛠️📤

Selecting data 📊

Selecting related data is easy in embedded records, for related tables, you need to use aggregators. 📊📁


You must make careful decisions at the time of table creation, keeping in mind which approach will work best for you. 🤓📅

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics