Get number of documents in collection firestore

Question:

Is it possible to count how many documents a collection in Firestore has, using python?

I just found this code

    functions.firestore.document('collection/{documentUid}')
    .onWrite((change, context) => {

    if (!change.before.exists) {
        // New document Created : add one to count

        db.doc(docRef).update({numberOfDocs: FieldValue.increment(1)});
    
    } else if (change.before.exists && change.after.exists) {
        // Updating existing document : Do nothing

    } else if (!change.after.exists) {
        // Deleting document : subtract one from count

        db.doc(docRef).update({numberOfDocs: FieldValue.increment(-1)});

    }

return;
});

How I can do this with python?

Asked By: Philipp Storz

||

Answers:

Firestore (like many NoSQL databases) has no built in aggregation queries. If you want to determine the number of documents, you have two main options:

  1. Read all documents, and then count them in the client.
  2. Keep the document count in the database itself, and then update it with every add/delete operation.

While the firsts option is simpler, it is less scalable as you’ll end up with clients reading all documents just to determine the count. That’s why you’ll find most questions/articles about counting documents focusing on the second approach.

For more on this, see:

  • The Firestore documentation on aggregation queries.
  • The Firestore documentation on distributed counters, which you’ll need to consider if your count changes more frequently than about once per second.
Answered By: Frank van Puffelen

New in February 2023

Firestore now has added the count() method to queries and collections in the Python SDK.

Usage

The documentation does not say much about it at the moment, but here is how I manage to use it.

You need firebase-admin in 6.1.0 or later.

Init

from firebase_admin import firestore

# do the credentials stuff if necessary
db = firestore.client()

Count docs in collection

my_collection = db.collection("foo")
count_query = my_collection.count()
query_result = count_query.get()
print("Nb docs in collection:", query_result[0][0].value)

Count docs from query

simple_query = db.collection("foo").where("myField", "==", 0)
count_query = simple_query.count()
query_result = count_query.get()
print("Nb docs in query:", query_result[0][0].value)
Answered By: XGeffrier
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.