0
0
Firebasecloud~30 mins

Why compound queries narrow results in Firebase - See It in Action

Choose your learning style9 modes available
Why compound queries narrow results
📖 Scenario: You are managing a small online bookstore database using Firebase Firestore. You want to find books that match multiple conditions to help customers find exactly what they want.
🎯 Goal: Build a Firebase Firestore query that uses compound conditions to narrow down the list of books based on genre and price.
📋 What You'll Learn
Create a collection of books with fields: title, genre, and price
Add a configuration variable for the maximum price filter
Write a compound query filtering books by genre and price
Complete the query by adding a limit to the number of results
💡 Why This Matters
🌍 Real World
Online stores often need to filter products by multiple conditions to help customers find exactly what they want quickly.
💼 Career
Understanding compound queries is essential for cloud developers working with databases to efficiently retrieve relevant data.
Progress0 / 4 steps
1
Create the initial books collection data
Create a variable called books that is an array of objects. Each object should have these exact fields and values: { title: 'Book A', genre: 'fiction', price: 10 }, { title: 'Book B', genre: 'fiction', price: 15 }, { title: 'Book C', genre: 'non-fiction', price: 20 }, { title: 'Book D', genre: 'fiction', price: 25 }.
Firebase
Need a hint?

Use const books = [ ... ] with the exact objects inside.

2
Add a maximum price filter variable
Create a variable called maxPrice and set it to 20 to filter books by price.
Firebase
Need a hint?

Use const maxPrice = 20; exactly.

3
Write a compound query filtering by genre and price
Create a variable called filteredBooks that filters books to include only those with genre equal to 'fiction' and price less than or equal to maxPrice. Use the filter method with a function that checks both conditions.
Firebase
Need a hint?

Use books.filter(book => book.genre === 'fiction' && book.price <= maxPrice).

4
Limit the number of results returned
Create a variable called limitedBooks that contains the first 2 books from filteredBooks. Use the slice method to get the first 2 items.
Firebase
Need a hint?

Use filteredBooks.slice(0, 2) to get the first two books.