0
0
MongoDBquery~30 mins

Embedded documents (nested objects) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Create and Query Embedded Documents in MongoDB
📖 Scenario: You are building a small database for a bookstore. Each book has details like title, author, and price. Additionally, each book has an embedded document for the publisher information, which includes the publisher's name and address.
🎯 Goal: Create a MongoDB collection with embedded documents for publisher details. Then, write a query to find all books published by a specific publisher.
📋 What You'll Learn
Create a collection called books with documents containing title, author, price, and an embedded document publisher with name and address fields.
Add a variable targetPublisher to store the publisher name to search for.
Write a query to find all books where the embedded publisher.name matches targetPublisher.
Complete the query by projecting only the title and author fields in the output.
💡 Why This Matters
🌍 Real World
Many real-world databases store related information inside embedded documents to keep data organized and easy to access, like storing publisher details inside book records.
💼 Career
Understanding embedded documents and querying nested fields is essential for working with MongoDB and other NoSQL databases, a common skill in backend development and data engineering.
Progress0 / 4 steps
1
Create the books collection with embedded publisher documents
Create a variable called books and assign it an array with these two documents exactly:
1. { title: "The Great Gatsby", author: "F. Scott Fitzgerald", price: 10.99, publisher: { name: "Scribner", address: "New York" } }
2. { title: "1984", author: "George Orwell", price: 8.99, publisher: { name: "Secker & Warburg", address: "London" } }
MongoDB
Need a hint?

Use an array of objects. Each book object has a publisher object inside it.

2
Add a variable to hold the target publisher name
Create a variable called targetPublisher and set it to the string "Scribner".
MongoDB
Need a hint?

Use const targetPublisher = "Scribner"; to store the publisher name.

3
Write a query to find books by the target publisher
Write a variable called query that uses books.filter() to find all books where book.publisher.name equals targetPublisher.
MongoDB
Need a hint?

Use filter with a function checking book.publisher.name === targetPublisher.

4
Project only the title and author fields in the query result
Create a variable called result that maps over query to return objects with only title and author fields.
MongoDB
Need a hint?

Use map to create new objects with only title and author.