Firestore Queries

Firestore provides powerful query capabilities to retrieve specific documents from a collection or collection group.

1. Basic Queries

Use the query function along with where filters.

import { db } from "../lib/firebase";
import { collection, query, where, getDocs } from "firebase/firestore";

const q = query(collection(db, "cities"), where("capital", "==", true));
const querySnapshot = await getDocs(q);

querySnapshot.forEach((doc) => {
  console.log(doc.id, " => ", doc.data());
});

2. Query Operators

  • == : Equal to
  • != : Not equal to
  • < : Less than
  • <= : Less than or equal to
  • > : Greater than
  • >= : Greater than or equal to
  • array-contains : Matches if an array contains a specific value
  • in / not-in : Matches if the field is in a list of values

3. Simple Sort and Limit

import { orderBy, limit } from "firebase/firestore";

const q = query(
  collection(db, "cities"), 
  orderBy("name"), 
  limit(3)
);

4. Compound Queries

You can chain multiple where filters together.

const q = query(
  collection(db, "cities"), 
  where("state", "==", "CA"), 
  where("population", ">", 1000000)
);
Index Required: If you use multiple fields for equality and a range filter on another field (e.g., `==` and `>`), you may need to Create a Composite Index in the Firebase Console.