0
0
Firebasecloud~15 mins

Array-contains queries in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Array-Contains Queries in Firebase
📖 Scenario: You are building a simple app to manage a collection of books. Each book document in Firebase Firestore has a field called genres, which is an array of strings representing the genres the book belongs to.For example, a book might have genres: ['fiction', 'mystery'].
🎯 Goal: Learn how to query Firestore to find all books that belong to a specific genre using the array-contains query.
📋 What You'll Learn
Create a Firestore collection reference called books_ref pointing to the 'books' collection.
Create a variable called search_genre with the exact string value 'fiction'.
Write a Firestore query called query_ref that uses where with array-contains to find books where the genres array contains search_genre.
Add a final line to get the documents from query_ref using get().
💡 Why This Matters
🌍 Real World
Array-contains queries are useful when you want to find documents that have a specific value inside an array field, such as tags, categories, or genres.
💼 Career
Understanding how to query array fields in Firestore is important for building efficient and user-friendly apps that filter data based on user interests or categories.
Progress0 / 4 steps
1
Create Firestore collection reference
Create a Firestore collection reference called books_ref that points to the collection named 'books'.
Firebase
Need a hint?

Use firestore.collection('books') to get the collection reference.

2
Create search genre variable
Create a variable called search_genre and set it to the string 'fiction'.
Firebase
Need a hint?

Use const search_genre = 'fiction'; to create the variable.

3
Write array-contains query
Create a Firestore query called query_ref that uses books_ref.where with the field 'genres', the operator 'array-contains', and the value search_genre.
Firebase
Need a hint?

Use books_ref.where('genres', 'array-contains', search_genre) to create the query.

4
Get documents from query
Add a line to get the documents from query_ref by calling get() and assign it to a variable called query_snapshot.
Firebase
Need a hint?

Use await query_ref.get() to get the documents.