Avishay Cohen
Avishay Cohen

Reputation: 2218

firestore get all documents from collection using a single read action

currently i query my firestore db using the following query:

def get_db_from_cloud(self):
    """
    gets all the info in the db back to the flask app
    as a dictonary ready to be cached
    """
    docs = self.db.collection(self.collection_name).stream()

    docs_dict = {}

    for doc in docs:
        self.logger.debug(f'{doc.id} => {doc.to_dict()}')
        docs_dict[doc.id] = doc.to_dict()

    return docs_dict

this iterate over the collection in self.collection_name and returns me the correct information. When I analyze this i can see that the usage in my firestore usage dashboard is increased by the amount of docs i have. which make sense as i iterate over the whole collection. I search the API but couldn't find if it is possible to retrieve the whole collection using a single read operation.

As this specific collection is only changed by admins (and rarely), convenient to me to load the whole DB to cache on startup, and i would like to optimize it to cost as low as possible

so, is it possible? and if not, is there an alternative suggestion how to limit amount of read calls to the firestore?

Upvotes: 0

Views: 484

Answers (2)

Balanagu Yashwanth
Balanagu Yashwanth

Reputation: 329

To get first document from collection, please refer this - Same way you can loop and get other documents ids

collectionData = db.collection(uid).get()
print(collectionData[0].id)

Upvotes: -1

Doug Stevenson
Doug Stevenson

Reputation: 317467

With Firestore, it's not possible to query for multiple documents using a single read operation. A query will always be billed a number of reads that equals the number of documents returned (with a minimum cost of 1 read for queries that return no documents).

If you are trying to reduce the cost of storing and fetching this data, consider using a different product for that.

Upvotes: 1

Related Questions