Get number of documents in collection firestore

Viewed 922

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?

1 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.
Related