0
0
MongoDBquery~30 mins

One-to-many referencing pattern in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
One-to-many referencing pattern in MongoDB
📋 What You'll Learn
💡 Why This Matters
🌍 Real World
Many real-world applications store related data in separate collections or tables and link them using references. For example, a library system stores authors and books separately but connects them.
💼 Career
Understanding one-to-many referencing in MongoDB is essential for database design, data normalization, and efficient querying in backend 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 containing two author documents. Each author document must have an _id field with ObjectId values ObjectId("64b7f1a1f1a1f1a1f1a1f1a1") and ObjectId("64b7f1a1f1a1f1a1f1a1f1a2"), a name field with values "Jane Austen" and "Mark Twain", and a country field with values "UK" and "USA" respectively.
MongoDB
Need a hint?

Use a list of dictionaries. Use ObjectId for _id values exactly as shown.

2
Create the books collection with three books referencing authors
Create a variable called books that is a list containing three book documents. Each book document must have a title, a year, and an author_id field. Use the exact titles "Pride and Prejudice", "Emma", and "Adventures of Huckleberry Finn". Use years 1813, 1815, and 1884 respectively. Set author_id to reference the correct author's _id from the authors list created in Step 1.
MongoDB
Need a hint?

Use the ObjectId values from the authors list to set author_id in each book.

3
Insert the authors and books into MongoDB collections
Write two commands to insert the authors list into a collection called authors and the books list into a collection called books. Use the variable db for the database connection. Use insert_many() method for both collections.
MongoDB
Need a hint?

Use db.authors.insert_many(authors) and db.books.insert_many(books) to insert the lists into collections.

4
Query books with author details using the reference
Write a MongoDB aggregation query using db.books.aggregate() to join the books collection with the authors collection. Use $lookup to match books.author_id with authors._id. Store the result in a variable called books_with_authors. Use $unwind to flatten the joined author array.
MongoDB
Need a hint?

Use $lookup with from, localField, foreignField, and as. Then use $unwind on the joined field.