0
0
MongoDBquery~30 mins

Many-to-many with references in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Many-to-many with references in MongoDB
📖 Scenario: You are building a simple library database. Books can have multiple authors, and authors can write multiple books. You will create collections to store this many-to-many relationship using references.
🎯 Goal: Create two collections authors and books with references to each other to represent many-to-many relationships.
📋 What You'll Learn
Create an authors collection with documents containing _id and name fields.
Create a books collection with documents containing _id, title, and an author_ids array referencing authors._id.
Add a helper variable authorIds to store author ObjectIds for reference.
Insert sample data with two authors and two books, each book referencing one or more authors.
Add a final query to find all books with their author names using $lookup.
💡 Why This Matters
🌍 Real World
Many real-world databases have many-to-many relationships, like books and authors, students and courses, or products and categories.
💼 Career
Understanding how to model and query many-to-many relationships with references is essential for backend developers and database administrators working with MongoDB.
Progress0 / 4 steps
1
Create the authors collection with two authors
Create a variable called authors that is an array with two author documents. Each document should have an _id field with values 1 and 2, and a name field with values 'Alice Walker' and 'James Baldwin' respectively.
MongoDB
Need a hint?

Use a list of dictionaries with exact _id and name values.

2
Create the books collection with references to authors
Create a variable called books that is an array with two book documents. Each document should have an _id, a title, and an author_ids array referencing the author _id values. Use author_ids as the field name for references.
MongoDB
Need a hint?

Use exact _id and title values and reference author _id in author_ids array.

3
Add a helper variable authorIds for author references
Create a variable called authorIds that is a dictionary mapping author names to their _id values from the authors array. Use the exact keys 'Alice Walker' and 'James Baldwin'.
MongoDB
Need a hint?

Use a dictionary with exact keys and values matching author _id.

4
Add a MongoDB aggregation query to join books with author names
Create a variable called booksWithAuthors that contains a MongoDB aggregation pipeline using $lookup to join books with authors on author_ids and _id. The pipeline should add a field authors with author documents.
MongoDB
Need a hint?

Use a list with one dictionary containing the $lookup stage with exact keys and values.