/firebase-tutorials

How to query documents in Firestore?

Learn to query Firestore documents: Firebase setup, basic & compound queries, real-time updates, sorting, and error handling.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to query documents in Firestore?

 

Step 1: Set Up Firebase in Your Project

 

Before you can query documents in Firestore, you need to set up a Firebase project and integrate Firebase into your application. Follow the Firebase documentation to add the Firebase SDK to your application.

 

Step 2: Initialize Firestore

 

After setting up Firebase, initialize Firestore in your application. Ensure you import the necessary Firestore libraries.


// Import the functions you need from the SDK
import { getFirestore } from "firebase/firestore";

// Initialize Firestore
const db = getFirestore();

 

Step 3: Import Firestore Functions

 

You'll need to import the functions necessary to query documents from Firestore. These functions will depend on the types of queries you want to perform.


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

 

Step 4: Perform Basic Queries

 

To query documents in Firestore, you need to specify the collection and the conditions of the query.


// Define the collection and the query
const q = query(collection(db, "users"), where("age", "==", 25));

// Execute the query
const querySnapshot = await getDocs(q);

// Process the results
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

 

Step 5: Perform Compound Queries

 

Firestore allows for compound queries, where you can chain multiple conditions together.


// Chain multiple conditions in a single query
const q = query(
  collection(db, "users"),
  where("age", ">", 20),
  where("status", "==", "active")
);

// Execute the query
const querySnapshot = await getDocs(q);

// Process the results
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

 

Step 6: Use Order and Limit

 

You can sort query results and limit the number of results returned.


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

// Define a query with sorting and limiting
const q = query(
  collection(db, "users"),
  orderBy("age"),
  limit(5)
);

// Execute the query
const querySnapshot = await getDocs(q);

// Process the results
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});

 

Step 7: Query in Real-time

 

To listen for real-time updates instead of executing one-time queries, use the onSnapshot function.


import { onSnapshot } from "firebase/firestore";

// Set up a real-time listener for a query
const q = query(collection(db, "users"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
  querySnapshot.forEach((doc) => {
    console.log(`${doc.id} => ${doc.data()}`);
  });
});

// Call unsubscribe() to stop listening to real-time updates

 

Step 8: Handle Errors

 

While querying, handle errors that might occur using try-catch blocks.


try {
  const q = query(collection(db, "users"), where("age", ">", 20));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(`${doc.id} => ${doc.data()}`);
  });
} catch (error) {
  console.error("Error querying documents: ", error);
}

 

By following these steps, you can perform queries on your Firestore database, ranging from basic to more advanced real-time queries, ensuring you can access and manipulate your data efficiently.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022