0
0
FirebaseHow-ToBeginner · 4 min read

How to Query Documents in Firestore: Simple Guide

To query documents in Firestore, use the collection() method to select a collection, then apply where() filters to specify conditions. Finally, call get() or getDocs() to retrieve matching documents as a snapshot.
📐

Syntax

Firestore queries start by selecting a collection with collection(). You can add filters using where() to specify field conditions. Use orderBy() to sort results and limit() to restrict the number of documents returned. Finish by calling get() or getDocs() to fetch the documents.

  • collection('name'): selects the collection
  • where('field', 'operator', value): filters documents
  • orderBy('field'): sorts documents
  • limit(number): limits results
  • get() or getDocs(): retrieves documents
javascript
const querySnapshot = await firestore.collection('users')
  .where('age', '>=', 18)
  .orderBy('age')
  .limit(10)
  .get();
💻

Example

This example queries the users collection for users aged 18 or older, orders them by age, and limits the results to 10 documents. It then prints each user's name and age.

javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, query, where, orderBy, limit, getDocs } from 'firebase/firestore';

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function queryUsers() {
  const usersRef = collection(db, 'users');
  const q = query(usersRef, where('age', '>=', 18), orderBy('age'), limit(10));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(`${doc.data().name} is ${doc.data().age} years old`);
  });
}

queryUsers();
Output
Alice is 18 years old Bob is 20 years old Carol is 22 years old ... (up to 10 users)
⚠️

Common Pitfalls

Common mistakes include:

  • Not creating an index for complex queries with multiple where() or orderBy() clauses, which causes errors.
  • Using where() with unsupported operators or mismatched data types.
  • Forgetting to use orderBy() when using inequality filters like >=.
  • Not awaiting the get() or getDocs() call, leading to unresolved promises.
javascript
/* Wrong: Missing orderBy with inequality filter */
const qWrong = query(collection(db, 'users'), where('age', '>=', 18));

/* Right: Add orderBy on the same field */
const qRight = query(collection(db, 'users'), where('age', '>=', 18), orderBy('age'));
📊

Quick Reference

MethodPurposeExample
collection('name')Selects a collectioncollection(db, 'users')
where(field, op, value)Filters documentswhere('age', '>=', 18)
orderBy(field)Sorts documentsorderBy('age')
limit(number)Limits number of resultslimit(10)
getDocs(query)Fetches documentsconst snapshot = await getDocs(q)

Key Takeaways

Use collection(), where(), orderBy(), and limit() to build Firestore queries.
Always call getDocs() with await to retrieve query results.
Add orderBy() on the same field when using inequality filters like >= or <.
Create Firestore indexes for queries with multiple filters or sorting.
Check data types and operators carefully to avoid query errors.