How to Get Multiple Documents by Multiple IDs in One Query in Google Firestore

To get multiple documents by multiple ids in a single query in Google Firestore, you can use the “in” with the where clause.

Here’s how you can do this using JavaScript:

Step 1: Initialize a Firebase and import the necessary libraries

First, make sure you have initialized Firebase and imported the libraries needed.

const firebase = require("firebase/app");
require("firebase/firestore");

const firebaseConfig = {
  // Your Firebase configuration goes here
};
firebase.initializeApp(firebaseConfig);

const db = firebase.firestore();

Step 2: Create a function that retrieves several documents by their ids

Create a function that retrieves several documents by their IDs using the in operator.

async function getDocumentsByIds(collection, ids) {
  try {
    const querySnapshot = await db
     .collection(collection)
     .where(firebase.firestore.FieldPath.documentId(), "in", ids)
     .get();

   return querySnapshot.docs.map((doc) => {
     return { id: doc.id, data: doc.data() };
   });
  } catch (error) {
    console.error("Error getting documents by IDs:", error);
    return [];
  }
}

Step 3: Use the getDocumentsByIds() function to retrieve several documents by their IDs

async function main() {
  const collection = "your_collection_name";
  const ids = ["id1", "id2", "id3"]; // Replace with your document IDs
 
  const documents = await getDocumentsByIds(collection, ids);
  console.log("Documents:", documents);
 }
 
 main();

This example demonstrates how to get several documents by their IDs in a single query using the in operator in Google Firestore.

The getDocumentsByIds() function takes a collection name, and an array of document IDs retrieves the corresponding documents and returns an array of objects containing the document IDs and their data.

Please note that the “in operator” is limited to up to 10 IDs per query. Therefore, if you need to query more than 10 document IDs, you’ll need to split the IDs into chunks of 10, perform multiple queries, then combine the results.

That’s it.

Leave a Comment