0
0
MongoDBquery~30 mins

Projection for reducing data transfer in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Projection for Reducing Data Transfer in MongoDB
📖 Scenario: You work for a small online bookstore. The database has a collection called books with many details about each book, including title, author, year, price, and description. You want to show a list of books on the website but only need the title and author to reduce the amount of data sent from the database.
🎯 Goal: Build a MongoDB query that uses projection to return only the title and author fields from the books collection, excluding all other fields.
📋 What You'll Learn
Create a books collection with 3 documents containing title, author, year, price, and description fields.
Create a variable called projection that includes only title and author fields.
Write a query using find() on books with the projection to get only those fields.
Add a final command to convert the query result to an array.
💡 Why This Matters
🌍 Real World
Projection helps reduce the amount of data sent from the database to the application, making web pages load faster and saving bandwidth.
💼 Career
Database developers and backend engineers use projection to optimize queries and improve application performance.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a variable called books and assign it an array with these 3 documents exactly: { title: "The Hobbit", author: "J.R.R. Tolkien", year: 1937, price: 15.99, description: "A fantasy novel." }, { title: "1984", author: "George Orwell", year: 1949, price: 12.99, description: "A dystopian novel." }, { title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960, price: 14.99, description: "A novel about racial injustice." }
MongoDB
Need a hint?

Use an array of objects with the exact fields and values given.

2
Create the projection variable to select only title and author
Create a variable called projection and set it to an object that includes title and author with value 1 to include them in the query result.
MongoDB
Need a hint?

Use 1 to include fields in MongoDB projection.

3
Write the query using find() with the projection
Write a query using db.books.find({}, projection) to get only the title and author fields from the books collection.
MongoDB
Need a hint?

Use empty filter {} to select all documents and pass projection as second argument.

4
Convert the query result to an array
Add .toArray() to the query to get the results as an array and assign it to a variable called result.
MongoDB
Need a hint?

Use .toArray() to get all documents from the cursor as an array.