Home  >  Q&A  >  body text

Google Firestore - How to get multiple documents by multiple IDs in one round trip?

<p>I was wondering if it is possible to get multiple documents by a list of IDs in one round trip (network call) to the Firestore database. </p>
P粉536532781P粉536532781420 days ago426

reply all(2)I'll reply

  • P粉633075725

    P粉6330757252023-08-28 12:45:41

    Actually, you would use firestore.getAll like this

    async getUsers({userIds}) {
        const refs = userIds.map(id => this.firestore.doc(`users/${id}`))
        const users = await this.firestore.getAll(...refs)
        console.log(users.map(doc => doc.data()))
    }
    

    Or use Promise syntax

    getUsers({userIds}) {
        const refs = userIds.map(id => this.firestore.doc(`users/${id}`))
        this.firestore.getAll(...refs).then(users => console.log(users.map(doc => doc.data())))
    }
    

    reply
    0
  • P粉860370921

    P粉8603709212023-08-28 12:42:52

    If you are in Node:

    https://github.com/ googleapis/nodejs-firestore/blob/master/dev/src/index.ts#L978

    /**
    * Retrieves multiple documents from Firestore.
    *
    * @param {...DocumentReference} documents - The document references
    * to receive.
    * @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
    * contains an array with the resulting document snapshots.
    *
    * @example
    * 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])}`);
    * });
    */
    

    This is specifically for the server SDK

    Update: Cloud Firestore now supports IN queries!

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

    reply
    0
  • Cancelreply