How to Get All Documents from A Collection in a FireStore – Definitive Guide

Firestore allows you to store data in a document format, and documents are grouped into collections.

You can get all documents from a collection in a Firestore using the getDocs(collection(db, “collection_name”)) method.

This tutorial teaches you how to get all documents from a collection in a Firestore using the getDocs() method, get all documents from a subcollection in a Firestore and get multiple documents from a collection.

Prerequisite

  • Install the Firebase app using the following code:
npm install firebase
  • The Firebase configuration object with the necessary credentials to connect to your Firebase project. Read about firebase configuration object to know about the configuration objects.
  • Add Firestore security rules to enable the read document access.
  • The security rule must look like the following one.
rules_version = '2';

service cloud.firestore {

  match /databases/{database}/documents {

    match /{document=**} {

      allow read, write: if true;

    }


  }

}

Now let us learn how to get the documents from a collection.

Getting All Documents From A Collection In FireStore using getDocs() Method

To get all the documents from a collection, follow the steps:

  • Import the initializeApp function from the firebase/app package
  • Import the getFirestore, collection, and getDocs functions from the firebase/firestore package
  • Add the Firebase configuration to a variable
  • Initialize the Firebase app using const app = initializeApp(firebaseConfig)
  • Get the Firestore of the Firebase app using the getFireStore() method and store it in the db object.
  • Create a Firestore collection using the firestore object and the collection name from which you need to get the documents. For example, To get the documents from the collection called cities, create a collection object using collection(db, "cities”)
  • Pass the collection object to the getDocs() function. It will return a query snapshot of the firestore documents
  • Iterate over the snapshot and get the desired document properties.

Code

The following code demonstrates how to get all documents from a collection called cities.

import { initializeApp } from "firebase/app";

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

const firebaseConfig = {
  apiKey: “<your_api_key>“,
  authDomain: “<your_auth_domain>“,
  projectId: “<your_project_id>”,
  storageBucket: “<your_Storage_bucket>“,
  messagingSenderId: “<sender_id>“,
  appId: “<your_app_id>“,
  measurementId: “<your_measurement_id>“
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore(app);

async function quickstart() {

  const querySnapshot = await getDocs(collection(db, "cities"));

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

}

quickstart();

Output

chennai  =>  { shortcode: 'mas' }

coimbatore  =>  { shortcode: 'cbe' }

erode  =>  { pincode: 641109 }

Getting All Documents in a Sub Collection using getDocs() Method

To get all the documents in a sub-collection using the getDocs() method,

  • Create a collection object using the subcollection path. The subcollection path in the firestore looks like: cities\coimbatore\villages
  • For example, to get the documents from the subcollection villages, which is available in the main collection cities and the document coimbatore, create a collection object using collection(db, "cities", "coimbatore", "villages”)
  • Pass the collection object to the getDocs() method, which will return the query snapshot of the documents available in the subcollection.

Code

The following code demonstrates how to get the documents from the subcollection using the getDocs() method.

import { initializeApp } from "firebase/app";

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

const firebaseConfig = {
  apiKey: “<your_api_key>“,
  authDomain: “<your_auth_domain>“,
  projectId: “<your_project_id>”,
  storageBucket: “<your_Storage_bucket>“,
  messagingSenderId: “<sender_id>“,
  appId: “<your_app_id>“,
  measurementId: “<your_measurement_id>“
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore(app);

async function quickstart() {

  const querySnapshot = await getDocs(collection(db, "cities", "coimbatore", "villages"));

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

quickstart();

Output

gandhipuram  =>  { pincode: 641109 }

rspuram  =>  { pincode: 641002 }

Getting Multiple Documents from FireStore Using getDocs() Method

To get multiple documents from FireStore using the getDocs() method, you need to use the query() object.

  • In the query method, use the where clause and specify the fields and the values to filter the documents based on that filter value.
  • For example, to get the documents that have the shortcode value as cbe, use the query: query(collection(db, "cities"), where("shortcode", "==", "cbe”))
  • Pass the query object to the getDocs() method and get the query snapshot to iterate over the retrieved document.

Code

The following code demonstrates how to get multiple documents using the query method.

import { initializeApp } from "firebase/app";

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

const firebaseConfig = {
  apiKey: “<your_api_key>“,
  authDomain: “<your_auth_domain>“,
  projectId: “<your_project_id>”,
  storageBucket: “<your_Storage_bucket>“,
  messagingSenderId: “<sender_id>“,
  appId: “<your_app_id>“,
  measurementId: “<your_measurement_id>“
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const db = getFirestore(app);

async function quickstart() {

  const q = query(collection(db, "cities"), where("shortcode", "==", "cbe"));

  const querySnapshot = await getDocs(q);

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

quickstart();

Output

coimbatore  =>  { shortcode: 'cbe' }

This is how you can get documents from a Firestore collection.

Additional Resources

Leave a Comment