Search code examples
pythongoogle-cloud-firestorefirebase-admin

How to count number of fields those have same values in firstore using Python


I want to count the number of fields named 'In' with the value true in my firestore database.

Sample Database

This is How the Database has been linked in .py

def build(self):
    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import firestore

    cred = credentials.Certificate("cred.json")
    firebase_admin.initialize_app(cred)

    self.db = firestore.client()

    self.screen_manager.add_widget(Builder.load_file('kv/main.kv'))
    return self.screen_manager

But I have no idea to count it. Please help me to find a way.


Solution

  • Based on the Python examples in the Firebase documentation on querying Firestore, that should be something like:

    cities_ref = db.collection(u'Users')
    
    query_ref = cities_ref.where(u'In', u'==', true)
    
    docs = query_ref.get()
    
    print(len(docs))
    
    for doc in docs:
        print(f'{doc.id} => {doc.to_dict()}')