Archid Vignesh
Archid Vignesh

Reputation: 35

How to get the count of data under a document under a collection?

I have a collection called "user-followers". I basically need to display the total number of followers. Just not able to figure out the completion block to get the count. There are resources that help me get the count of the documents under a collection but what about the values inside a document. This is how the data is stored in firestore:

Collection: "user-followers"
 Document: "abc"
  "user1":1
  "user2":1
  "user3":1

I want the count of the number of users under document "abc", which is 3.

There are resources for getting count of all the documents but what about the count of data inside the document.

Upvotes: 0

Views: 373

Answers (2)

andresmijares
andresmijares

Reputation: 3744

This feature is not supported by default, but you have several ways to go around that. (unless you are ok querying the whole collection to get the numbers of records... this means everything, literally everything)

  • Cloud Functions
 import * as functions from 'firebase-functions' 
 import * as admin from 'firebase-admin' 
 const firestore = admin.firestore()
 const counterRef =  firestore.collection(`counters`)
 export const keepCount = functions
  .firestore.document(`user-followers/{doc}`).onWrite(async (change, _context) => {
    const oldData = change.before
    const newData = change.after
    const data = newData.data()

    if (!oldData.exists && newData.exists) {
        // creating
        return counterRef.doc(`user-followers`).set({
          counter: firebase.firestore.FieldValue.increment(1)
        })
      } else if (!newData.exists && oldData.exists) {
        // deleting
        return return counterRef.doc(`user-followers`).set({
          counter: firebase.firestore.FieldValue.increment(-1)
        })ID)
      } else  {
        // updating - do nothing
        return Promise.resolve(true)
    }
})

Now you only have to fetch counters collection, the doc value is your collection name user-followers, and the prop is counter... you can apply this patter with all the collections you need to keep track of the counter...

  • Other third-party cache tools

You always can use other tools like algolia or redis to keep track of this, but well they cost more money.

I would apply the cloud function to get started.

Upvotes: 1

Jay
Jay

Reputation: 35648

I am not sure storing your data like that is the best idea but it appears you are asking how to get a count of the fields within a document.

A simple solution is to count the child data, which will be three in this case.

func countFields() {
    let collectionRef = self.db.collection("user-followers")
    let documentRef = collectionRef.document("doc")
    documentRef.getDocument(completion: { documentSnapshot, error in
        if let error = error {
            print(error.localizedDescription)
            return
        }

        let q = documentSnapshot?.data()?.count
        print(q)
    })
}

The documentSnapshot?.data() is a dictionary which can be iterated over, counted etc.

Upvotes: 1

Related Questions