0
0
MongoDBquery~30 mins

Subset pattern for large documents in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Subset Pattern for Large Documents in MongoDB
📖 Scenario: You work at a library that stores detailed book information in a MongoDB collection. Each book document contains many fields, including a large reviews array with hundreds of entries. To improve performance when showing book summaries, you want to fetch only a subset of fields, excluding the large reviews array.
🎯 Goal: Build a MongoDB query that retrieves only the title, author, and year fields from the books collection, excluding the reviews field to reduce data size.
📋 What You'll Learn
Create a books collection with three book documents including title, author, year, and reviews fields
Define a projection object to exclude the reviews field
Write a MongoDB query using find() with the projection to get only the subset of fields
Complete the query to return the cursor for further processing
💡 Why This Matters
🌍 Real World
Large documents with many fields or arrays can slow down queries and increase network load. Using the subset pattern by excluding large fields helps improve performance when only summary data is needed.
💼 Career
Database developers and administrators often optimize queries by projecting only necessary fields, especially when working with large documents in MongoDB or similar NoSQL databases.
Progress0 / 4 steps
1
Create the books collection with sample documents
Create a variable called books and assign it an array with these three objects exactly: { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925, reviews: ['Excellent', 'Classic', 'Must read'] }, { title: '1984', author: 'George Orwell', year: 1949, reviews: ['Thought-provoking', 'Dystopian', 'Timeless'] }, { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960, reviews: ['Powerful', 'Emotional', 'Important'] }
MongoDB
Need a hint?

Use a list of dictionaries with exact keys and values as shown.

2
Define a projection to exclude the reviews field
Create a variable called projection and set it to an object that excludes the reviews field by setting reviews: 0
MongoDB
Need a hint?

Use { 'reviews': 0 } to exclude the reviews field in MongoDB projection.

3
Write the MongoDB find() query with the projection
Create a variable called query and assign it the result of calling db.books.find({}, projection) to fetch all documents but only the subset of fields
MongoDB
Need a hint?

Use db.books.find({}, projection) to get all documents with the projection applied.

4
Complete the query to return the cursor for further use
Add a line to assign result to the cursor returned by query so it can be used later for iteration
MongoDB
Need a hint?

Assign the cursor returned by find() to a variable called result.