Home >Web Front-end >JS Tutorial >How to Efficiently Retrieve Multiple Firestore Documents by ID in a Single Request?

How to Efficiently Retrieve Multiple Firestore Documents by ID in a Single Request?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 19:45:22846browse

How to Efficiently Retrieve Multiple Firestore Documents by ID in a Single Request?

How to Retrieve Multiple Documents by IDs in a Single Request with Google Firestore

To efficiently retrieve multiple documents based on their IDs in a single network call, consider the following approaches:

Node.js:

const getAll = (...documents) =>
  Promise.all(documents.map(doc => doc.get()));

Call getAll() passing in the desired DocumentReference objects:

let documentRef1 = firestore.doc('col/doc1');
let documentRef2 = firestore.doc('col/doc2');

firestore.getAll(documentRef1, documentRef2).then(docs => {
  console.log(`First document: ${JSON.stringify(docs[0])}`);
  console.log(`Second document: ${JSON.stringify(docs[1])}`);
});

Server SDK (Python):

def get_all(client, *docs):
  return client.get_all(docs)

docs = (
    db.collection(u'users').document(u'alovelace'),
    db.collection(u'users').document(u'aturing'),
    db.collection(u'users').document(u'hopper'),
)
docs_iterator = get_all(client, *docs)

IN Queries:

Firestore now supports IN queries, allowing you to retrieve documents filtered by a list of IDs efficiently:

myCollection.where(firestore.FieldPath.documentId(), 'in', ["123", "456", "789"])

The above is the detailed content of How to Efficiently Retrieve Multiple Firestore Documents by ID in a Single Request?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn