Schema Design from a Relational Database to MongoDB

Let’s take the following example, where to get the full information from an employee we would need to query three different tables with joins to get his phone numbers and his company.

unnamed 31

If we wanted we could easily reproduce this schema in Mongo creating a collection for each of the tables, using IDs to create references, and JOINING them via aggregation with the command $lookup, but is this the best solution?

Well no, it could probably cause performance issues down the line as $lookup operations are expensive and we cannot take advantage of indexes if there are more steps to the aggregation.

With MongoDB, you may embed related data in a single structure or document. These schemas are generally known as “denormalized” models, and take advantage of MongoDB’s rich documents.

So how would this model look with the information embedded:

unnamed 32

Embedded data models allow applications to store related pieces of information in the same database record. As a result, applications may need to issue fewer queries and updates to complete common operations. In our example with just looking for the employee we will get his related phone numbers and his company.

 
Scroll to Top