0
0
MongoDBquery~30 mins

Querying nested fields at any depth in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Querying Nested Fields at Any Depth in MongoDB
📖 Scenario: You are managing a MongoDB collection that stores information about books in a library. Each book document contains nested fields for details like author information and publisher contacts. You want to learn how to query these nested fields no matter how deeply they are nested.
🎯 Goal: Build a MongoDB query that finds all books where the publisher's contact email matches a specific value, demonstrating how to query nested fields at any depth.
📋 What You'll Learn
Create a collection named books with nested documents for author and publisher.
Add a configuration variable for the target publisher email to search for.
Write a MongoDB query that finds all books with the publisher's contact email matching the target email.
Complete the query by projecting only the book title and publisher contact email.
💡 Why This Matters
🌍 Real World
Many real-world databases store complex nested data like user profiles, product details, or logs. Knowing how to query nested fields helps you find exactly what you need quickly.
💼 Career
Database developers and data analysts often work with nested JSON-like data in MongoDB. Mastering nested queries is essential for efficient data retrieval and manipulation.
Progress0 / 4 steps
1
DATA SETUP: Create the books collection with nested fields
Create a MongoDB collection called books and insert these two documents exactly:
1) { title: "Learn MongoDB", author: { name: "Alice" }, publisher: { name: "TechBooks", contact: { email: "contact@techbooks.com" } } }
2) { title: "Advanced Databases", author: { name: "Bob" }, publisher: { name: "DataPress", contact: { email: "info@datapress.com" } } }
MongoDB
Need a hint?

Use db.books.insertMany() with an array of two documents matching the exact structure and values.

2
CONFIGURATION: Define the target publisher email to search for
Create a variable called targetEmail and set it to the string "contact@techbooks.com".
MongoDB
Need a hint?

Use const targetEmail = "contact@techbooks.com"; to define the variable.

3
CORE LOGIC: Write a query to find books by publisher contact email
Write a MongoDB query using db.books.find() to find all documents where the nested field publisher.contact.email equals the variable targetEmail.
MongoDB
Need a hint?

Use dot notation in the query object: { "publisher.contact.email": targetEmail }.

4
COMPLETION: Project only the book title and publisher contact email
Complete the query by adding a projection to return only the title and publisher.contact.email fields.
MongoDB
Need a hint?

Use the second argument of find() to specify the projection fields.