0
0
Firebasecloud~30 mins

Collection group queries in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Collection Group Queries in Firebase
📖 Scenario: You are building a simple app to track user comments on different posts. Each post has its own collection of comments stored in subcollections. You want to find all comments across all posts that contain a specific keyword.
🎯 Goal: Build a Firebase query that uses a collection group query to find all comments containing the word "great" in their text, regardless of which post they belong to.
📋 What You'll Learn
Create a Firestore collection called posts with at least two documents.
Each posts document should have a subcollection called comments with comment documents.
Create a variable called keyword set to the string "great".
Write a collection group query on comments to find all comments where the text field contains the keyword.
Store the query in a variable called query.
💡 Why This Matters
🌍 Real World
Collection group queries let you search across many subcollections with the same name, useful for apps with nested data like comments on posts or reviews on products.
💼 Career
Understanding collection group queries is important for building scalable, efficient Firestore apps that need to search data across multiple nested collections.
Progress0 / 4 steps
1
Set up Firestore data structure
Create a Firestore collection called posts with two documents having IDs post1 and post2. Each post document should have a subcollection called comments with two comment documents. The comments should have a text field with these exact values:

- For post1/comments: comment1 with text "This is great!", comment2 with text "Nice work"
- For post2/comments: comment1 with text "Great job", comment2 with text "Needs improvement"
Firebase
Need a hint?

Use firestore.collection('posts') to get the posts collection. Then use doc() and collection('comments') to add comments.

2
Create a keyword variable
Create a variable called keyword and set it to the string "great".
Firebase
Need a hint?

Use const keyword = 'great'; to create the variable.

3
Write the collection group query
Write a collection group query on comments to find all documents where the text field contains the keyword. Store this query in a variable called query. Use firestore.collectionGroup('comments') and a where clause with array-contains or >= and <= operators to filter text containing the keyword.
Firebase
Need a hint?

Use firestore.collectionGroup('comments') and chain two where clauses with >= and <= to filter text starting with the keyword.

4
Complete the query setup
Add a line to execute the query and store the results in a variable called results. Use await query.get() to fetch the documents.
Firebase
Need a hint?

Use const results = await query.get(); to fetch the matching documents.