0

Is there anyway to read the length of a collection? For example, if a collection (users) has 1,000 users, can I make a request for the collection length? I know collection items are index, so not sure if that makes it easier to count reads with out wasting 1,000 reads.

The main purpose of the collection length is that I have an admin dashboard and I want to display how many users we have in Cloud Firestore.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
jefelewis
  • 1,850
  • 1
  • 27
  • 63
  • If you want a count without reading everything, you will need to keep track of it yourself. Firestore cannot do that for free at massive scale. – Doug Stevenson Jun 24 '20 at 18:02

1 Answers1

0

This is not possible by default, however, you could keep a doc/collection to hold metadata associated with collections, in this specific case you can use a distributed counter.

The idea is to have a cloud function which listens for onWrite events and increase or decrease the counter, I cannot recall the code exactly but it would be something like this:

  const metadataCollectionRef = firebase.firestore().collection(`metadata`).doc(`users`)

  export const myCollectionCounter = functions
  .firestore.document(`users/{doc}`).onWrite(async (change, _context) => {
    const oldData = change.before
    const newData = change.after
    const data = newData.data()

    if (!oldData.exists && newData.exists) {
        // creating
        return metadataCollectionRef.set({
          count: FieldValue.increment(1)
        }, {merge: true})
      } else if (!newData.exists && oldData.exists) {
        // deleting
        return metadataCollectionRef.set({
          count: FieldValue.increment(-1)
        }, {merge: true})
      } 
})

This should give you enough information to get started. Docs are here

andresmijares
  • 3,658
  • 4
  • 34
  • 40