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.
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
_id
of the parent document can be stored in multiple related documents, or an array of related document identifiers can be stored in the parent document.
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:
JavaScript1use library_db 2 3db.books.insertOne({ 4 title: "To Kill a Mockingbird", 5 author: "Harper Lee", 6 reviews: [ 7 { 8 reviewer: "John Doe", 9 rating: 5, 10 comment: "An exceptional read!", 11 review_date: new Date(2020, 1, 1) 12 }, 13 { 14 reviewer: "Jane Smith", 15 rating: 4, 16 comment: "A timeless classic.", 17 review_date: new Date(2021, 2, 15) 18 } 19 ] 20});
In this code snippet:
- We insert a book document into the
books
collection usinginsertOne()
. - The document contains
title
,author
, andreviews
fields. Thereviews
field 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.
Using references becomes beneficial when the "many" side of the relation grows significantly or when multiple documents need to link to the same data. References store the _id
value of one document in another, maintaining normalized data and avoiding duplicity.
Here's an example using references to represent a book and its reviews:
JavaScript1use library_db 2 3const bookId = new ObjectId(); 4db.books.insertOne({ _id: bookId, title: "1984", author: "George Orwell" }); 5 6db.reviews.insertMany([ 7 { 8 reviewer: "Alice Brown", 9 rating: 5, 10 comment: "Profoundly impactful.", 11 review_date: new Date(2019, 5, 20), 12 book_id: bookId 13 }, 14 { 15 reviewer: "Bob Green", 16 rating: 4, 17 comment: "Very thought-provoking.", 18 review_date: new Date(2020, 7, 10), 19 book_id: bookId 20 } 21]);
In this code snippet:
- We create a unique
ObjectId
for the book and store it inbookId
. - Using
insertOne()
, we add a book document to thebooks
collection with_id
set tobookId
,title
to "1984", andauthor
to "George Orwell". - Using
insertMany()
, we insert multiple review documents into thereviews
collection. Each review document includesreviewer
,rating
,comment
,review_date
, andbook_id
fields, the latter of which references the_id
of the book document.
There are several ways to maintain the link between the book and its reviews. You can store the book_id
in the reviews
collection, as shown above, or alternatively, you can store an array of review_ids
in the books
collection. Additionally, you can store references in both collections. The choice depends on your specific use case and how you intend to retrieve and manage the related data.
In this lesson, you learned about one-to-many relations in MongoDB and explored two methods to implement them: embedded documents and references. Use embedded documents when the related data isn't extensive and does not require linking from multiple documents. When the data volume is larger or needs to be referenced by multiple documents, opting for references is more appropriate. Up next, you'll get hands-on practice to solidify your understanding of these concepts. Keep coding and enjoy your MongoDB journey!