Philipp Storz
Philipp Storz

Reputation: 145

Get number of documents in collection firestore

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?

Upvotes: 8

Views: 4374

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598688

Firestore now has no limited support for aggregation queries.

Previous answer below, as this still applies for cases that are not supported.


Outside of the built-in count operation, 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:

Upvotes: 2

XGeffrier
XGeffrier

Reputation: 405

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.

from firebase_admin import firestore

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

# Count all 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 some docs via a query
any_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)

Upvotes: 13

Related Questions