0
0
MongoDBquery~30 mins

Embedding vs referencing decision in MongoDB - Hands-On Comparison

Choose your learning style9 modes available
Embedding vs Referencing Decision in MongoDB
📖 Scenario: You are building a simple online bookstore database using MongoDB. You want to store information about books and their authors. Each book has a title and an author. Each author has a name and a country.Sometimes authors write many books, and sometimes books have only one author. You want to decide whether to embed author details inside each book document or to reference authors separately.
🎯 Goal: Build two collections: authors and books. First, create author documents. Then create book documents that reference authors by their _id. This will help you understand referencing in MongoDB.
📋 What You'll Learn
Create an authors collection with two authors: 'Jane Austen' from 'UK' and 'Mark Twain' from 'USA'.
Create a books collection with two books: 'Pride and Prejudice' by Jane Austen and 'Adventures of Huckleberry Finn' by Mark Twain.
Use referencing by storing the author's _id inside each book document.
Do not embed author details inside the book documents.
💡 Why This Matters
🌍 Real World
Online bookstores and many other applications use referencing in MongoDB to keep data organized and avoid duplication.
💼 Career
Understanding embedding vs referencing is essential for designing efficient MongoDB databases in software development and data engineering roles.
Progress0 / 4 steps
1
Create the authors collection with two authors
Create a variable called authors that is a list of two dictionaries. The first dictionary should have 'name': 'Jane Austen' and 'country': 'UK'. The second dictionary should have 'name': 'Mark Twain' and 'country': 'USA'.
MongoDB
Need a hint?

Think of authors as a list of small address cards, each with a name and country.

2
Create a mapping from author names to their IDs
Create a variable called author_ids that is a dictionary mapping author names to unique string IDs. Use 'Jane Austen' mapped to 'a1' and 'Mark Twain' mapped to 'a2'.
MongoDB
Need a hint?

This dictionary helps you link books to authors by ID instead of repeating full author details.

3
Create the books collection referencing authors by ID
Create a variable called books that is a list of two dictionaries. The first dictionary should have 'title': 'Pride and Prejudice' and 'author_id': 'a1'. The second dictionary should have 'title': 'Adventures of Huckleberry Finn' and 'author_id': 'a2'.
MongoDB
Need a hint?

Each book stores only the author_id to link to the author, not the full author details.

4
Add the final step to simulate inserting documents into MongoDB
Create a variable called db that is an empty dictionary. Then add the authors list to db under the key 'authors' and the books list under the key 'books'.
MongoDB
Need a hint?

This simulates how MongoDB stores collections inside a database object.