Firebase Tutorial
- Home
- Introduction
- Project Setup
- Authentication (Email/Pass)
- Social Authentication
- Cloud Firestore (Basics)
- Firestore Queries
- Real-time Updates
- Firestore Security Rules
- Cloud Storage
- Storage Security Rules
- Cloud Functions (Intro)
- Triggering Functions
- Firebase Hosting
- Firebase Analytics
- Crashlytics & Performance
- Remote Config
- App Check
- Offline Persistence
- Firebase with Next.js
- Best Practices
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 toarray-contains: Matches if an array contains a specific valuein/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.