How to Use Collection Group Query in Firebase
Use
collectionGroup() from Firebase Firestore to query all collections with the same name across your database. This lets you search documents in subcollections without specifying exact paths.Syntax
The collectionGroup() method takes the collection name as a string and returns a query that searches all collections with that name anywhere in your Firestore database.
You then use where() to filter documents and get() to retrieve results.
javascript
const query = firestore.collectionGroup('collectionName').where('field', '==', 'value'); const snapshot = await query.get();
Example
This example queries all subcollections named comments across the database, filtering for documents where the approved field is true.
javascript
import { getFirestore, collectionGroup, query, where, getDocs } from 'firebase/firestore'; const firestore = getFirestore(); async function getApprovedComments() { const commentsQuery = query( collectionGroup(firestore, 'comments'), where('approved', '==', true) ); const querySnapshot = await getDocs(commentsQuery); querySnapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); }); } getApprovedComments();
Output
comment1 => { approved: true, text: 'Great post!' }
comment2 => { approved: true, text: 'Thanks for sharing.' }
Common Pitfalls
- Not indexing the collection group: Firestore requires an index for collection group queries; otherwise, it will show an error with a link to create the index.
- Using
collection()instead ofcollectionGroup()when you want to query all collections with the same name. - Trying to query across different collection names;
collectionGroup()only works for one collection name at a time.
javascript
/* Wrong: Queries only one collection path */ const wrongQuery = firestore.collection('comments').where('approved', '==', true); /* Right: Queries all 'comments' collections anywhere */ const rightQuery = firestore.collectionGroup('comments').where('approved', '==', true);
Quick Reference
- collectionGroup(name): Query all collections with the given name.
- where(field, op, value): Filter documents by field.
- get() or getDocs(): Retrieve query results.
- Ensure Firestore indexes are created for collection group queries.
Key Takeaways
Use collectionGroup() to query all collections with the same name across Firestore.
Always create required indexes for collection group queries to avoid errors.
collectionGroup() queries subcollections without needing full paths.
You can combine collectionGroup() with where() to filter results.
collectionGroup() only works for one collection name at a time.