How to Query Subcollection in Firestore: Simple Guide
To query a subcollection in Firestore, use
collection() on a document reference to access the subcollection, then apply get() or query methods like where(). For example, db.collection('users').doc('userId').collection('orders').get() fetches all orders for a user.Syntax
To query a subcollection in Firestore, first get a reference to the parent document using doc(). Then call collection() on that document reference to access the subcollection. Finally, use query methods like get() or where() to fetch documents.
db.collection('parentCollection'): Access the main collection..doc('docId'): Select a specific document..collection('subCollection'): Access the subcollection inside that document..where('field', '==', value): Filter documents in the subcollection..get(): Retrieve the documents matching the query.
javascript
const subcollectionRef = db.collection('parentCollection').doc('docId').collection('subCollection'); const querySnapshot = await subcollectionRef.where('field', '==', 'value').get();
Example
This example fetches all orders from the orders subcollection for a user with ID user123. It prints each order's ID and data.
javascript
import { getFirestore, collection, doc, getDocs } from 'firebase/firestore'; const db = getFirestore(); async function fetchUserOrders(userId) { const ordersRef = collection(doc(db, 'users', userId), 'orders'); const ordersSnapshot = await getDocs(ordersRef); ordersSnapshot.forEach(orderDoc => { console.log('Order ID:', orderDoc.id, 'Data:', orderDoc.data()); }); } fetchUserOrders('user123');
Output
Order ID: order1 Data: { item: 'Book', quantity: 2 }
Order ID: order2 Data: { item: 'Pen', quantity: 5 }
Common Pitfalls
Common mistakes when querying subcollections include:
- Trying to query a subcollection directly from
db.collection()without specifying the parent document. - Using incorrect document IDs or collection names.
- Not awaiting asynchronous calls, leading to empty results.
Always ensure you chain collection() after a doc() reference to target the subcollection correctly.
javascript
/* Wrong way: Trying to query subcollection directly */ const wrongRef = db.collection('orders'); // This accesses a top-level collection, not a subcollection /* Right way: Access subcollection via parent document */ const rightRef = db.collection('users').doc('user123').collection('orders');
Quick Reference
| Step | Description | Example |
|---|---|---|
| 1 | Access parent collection | db.collection('users') |
| 2 | Select parent document | .doc('user123') |
| 3 | Access subcollection | .collection('orders') |
| 4 | Apply query or get all | .where('status', '==', 'shipped').get() |
| 5 | Process results | snapshot.forEach(doc => console.log(doc.data())) |
Key Takeaways
Always access a subcollection through its parent document reference using doc() then collection().
Use query methods like where() on the subcollection reference to filter results.
Remember to await asynchronous calls to get data correctly.
Avoid querying subcollections as top-level collections directly.
Check collection and document names carefully to avoid errors.