One-to-One Relations in MongoDB
Introduction
Hello and welcome back! As a quick reminder, in our previous lesson, we learned about the essential data types that MongoDB supports. In this lesson, we'll delve into a crucial part of database design — relationships, specifically "One-to-One" relations. We will explore how to model data in MongoDB to represent one-to-one relationships using embedded documents and references, along with the advantages and disadvantages of each approach.
Data Modeling
Data modeling is the process of determining the best way to store data. In MongoDB, we have a lot of flexibility, but it's essential to understand this flexibility to avoid performance pitfalls. To determine the optimal way to store data, consider the following:
- Which data does your service use? This question helps you understand which collections you might need and which fields the documents in the collections will have. For example, if you're building a database for a Book Store, you'll probably need a
bookscollection with fields liketitle,description,price, andavailableQuantity. - Another important question is about the data you need in different components or pages of your app. As an example, let's consider the Book Store application again, where you have a Users List Page, User Details Page, Books List Page, and Book Details Page. You'll probably need at least two collections:
booksandusers. You can useusers.find()to display the data on the Users List Page andusers.findOne({_id: '<user_id>'})to display the data on the User Details Page. Similarly, you can usebooks.find()to display the data on the Books List Page andbooks.findOne({_id: '<book_id>'})to display the data on the Book Details Page.
What are Relations?
In databases, relationships denote how data entities are connected. Relations can be categorized into three primary types:
- One-to-One: A single entity A is related to a single entity B. For instance, every Book Store Customer has a unique Purchase History, and this particular Purchase History belongs exclusively to that Customer.
- One-to-Many: A single entity A is related to multiple entities in B. A good example would be reviews about the books. Every book can have reviews left by multiple users. However, a single review would not be associated with multiple books.
- Many-to-Many: Multiple entities in A are related to multiple entities in B. An example here would be the relations between books and authors. One author can write many books, and one book can have multiple co-authors.
In this lesson, we will focus on one-to-one relationships. We will dive into other types of relationships like one-to-many and many-to-many in subsequent lessons.
