One-to-Many Relations in MongoDB
Introduction
Welcome to the third lesson of our "Schemas and Relations" course! In our previous lessons, we covered MongoDB's flexible schema design and explored one-to-one relations. In this lesson, we will dive into the realm of one-to-many relations in MongoDB, examining how to model these relationships using both embedded documents and references.
What are One-to-Many Relations?
In a one-to-many relation, a single entity is related to multiple other entities. For example, consider a book that has multiple reviews. This establishes a one-to-many relation between a book and its reviews. Similarly to one-to-one relations, we can represent one-to-many relationship in two primary ways:
- Embedded Documents: The related data is included as an embedded array within the parent document.
- References: The
_idof the parent document can be stored in multiple related documents, or an array of related document identifiers can be stored in the parent document.
Representing One-to-Many Relations Using Embedded Documents
Embedded documents in MongoDB allow you to store related data within a parent document, making it easy to retrieve all the information in a single query. This method is suitable when the "many" side of the relation has a manageable number of elements.
Here's an example representing a book and its reviews using embedded documents:
In this code snippet:
- We insert a book document into the
bookscollection usinginsertOne(). - The document contains
title,author, andreviewsfields. Thereviewsfield is an array of embedded documents, each representing a review with fields likereviewer,rating,comment, andreview_date.
This setup efficiently represents the one-to-many relationship between a book and its reviews using embedded documents.
Representing One-to-Many Relations Using References
