Modern technology gives us many things.

Working With Data Relationships in MongoDB

0


MongoDB is a document database and doesn’t maintain relationships between documents like relational databases such as PostgreSQL.

Still, MongoDB allows you to create relationships between documents. These relationships can either be modeled through embedded or referenced approaches. Let’s take a closer look.

Embedded Relationships vs. Reference Relationships

In an embedded approach, a document is directly inserted inside another document, resulting in nested data. The process is also called “denormalization”.

The reference approach, on the other hand, uses document references to point from one document to another. This approach is also called “normalization”.

MongoDB: One-to-One Relationships With Embedded Documents

You can create a one-to-one relationship between documents using the embedded approach. This relationship occurs when one document object can only relate to one other document.

Consider a student database. This database contains the student and address collections with the following documents.

// Student Document
{
"studentName": "Frodo Baggins",
"phoneNumber": "987654321",
};
// Address Document
{
"studentName": "Frodo Baggins",
"street": "Bagshot Row",
"city": "Hobiton",
}

In this database, a student is allowed to have only one address. To retrieve the address, you’ll need to query the address collection using the student’s name.

MAKEUSEOF VIDEO OF THE DAY

Related: How to Create a Database and Collection in MongoDB

In cases where the address is used in tandem with other details such as a studentName, you will have to query the database multiple times. The downside of this is a high number of read operations and consequently low query performance.

Using the embedded approach, you can insert the address data right into the student document and use only a single query to get the data.

{
"studentName": "Frodo Baggins",
"phoneNumber": "987654321",
"address": [{
"street": "Bagshot Row",
"city": "Hobiton"
}],
};

To retrieve the address through the studentName, use this query.

db.student.findOne({"studentName":"Frodo Baggins"}, {"address":1})
Screenshot of terminal showing results from mongoDB query

One-to-Many Relationships With Embedded Documents in MongoDB

Consider a situation where a student has multiple addresses. The relationship between the student and the addresses becomes one-to-many.

The embedded model allows you to add multiple addresses to the student document. As in the one-to-one relationship using embedded documents, this approach has a relatively high query performance.

{
"studentName": "Frodo Baggins",
"phoneNumber": "987654321",
"address": [
{
"street": "Bagshot Row",
"city": "Hobiton"
},
{
"street": "Another Bagshot Row",
"city": "Hobiton2"
},
]
};


The query below will return the addresses of the specified student name.

db.student.findOne({studentName: “Frodo Baggins”}, {address: 1})
Terminal window showing output from MongoDB query

Related: How to Create Documents in MongoDB

Now, if you have more addresses and keep adding them to the address field, the document can become cluttered pretty quickly. One solution is to use document references.

MongoDB: One-to-Many Relationships With Document References

You can also model a one-to-many relationship using the reference approach. In this data model, the student and address data will be maintained in separate collections. To relate the student to their address, add a field containing the address IDs to the student document.

{
"studentName": "Frodo Baggins",
"phoneNumber": "987654321",
"address": [
ObjectId("61fa7bfeebdadf8ac71427ea"),
ObjectId("61fa7d19ebdadf8ac71427eb")
]
};


Getting the address details of a student involves fetching the address IDs from the student document and using those IDs to fetch the actual addresses from the collection.

const student = db.users.findOne({"name":"Frodo Baggins"},{"address":1})
const addresses = db.address.find({"_id":{"$in":student["address_ids"]}})
Terminal window showing results from MongoDB query

Choosing Between Embedded and Reference Approaches

Both the embedding and referencing models have their pros and cons, and you’ll have to consider a couple of things before making a choice. . For starters, you’ll need to consider the use case. If the data will only be related to one document, embedding could be your best option.

To create one-to-many relationships, you can use either the referencing model or the embedded model. Referencing results in a clean and consistent document since you only add the reference ID of the document you want to relate to.

However, the number of read operations required to retrieve the connected data is relatively high and can impact performance. Embedding the document may increase performance, but with many nested documents you might end up with a congested collection.

Choosing how to implement the data relationships in your document is therefore entirely up to you. Consider how you will use the document, the query performance level you’re aiming for, and the trade-offs you’re willing to make.


Old database with wooden drawers
How Is Data Modeling Different In MongoDB?

Considering a different approach to databases? Here’s how data modeling works in MongoDB.

Read Next


About The Author



Source link

Leave A Reply

Your email address will not be published.