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
Release: 2024-12-10 19:45:22
Original
858 people have browsed it

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()));
Copy after login

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])}`);
});
Copy after login

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)
Copy after login

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"])
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template