Jack tileman
Jack tileman

Reputation: 871

Check if the collection query returned a set of documents - Firestore python

According to documentation here to query a set of documents we need to use the collection query.

Once we execute the query. And use the following code to find if there are documents.

code_ref            = db.collection(u'col1')
 code_query          = code_ref.limit(1)        
 code_docs           = code_query.get()

code_docs_array = []
for elements in code_docs:
    code_docs_array.append(elements)

if (len(code_docs_array) > 0):
    # there are docs
else:                        
    # there are no docs

I am sure the above method is inefficient. Is there a equivalent to docs.exists function when dealing with collection query?

Upvotes: 0

Views: 35

Answers (1)

CaioT
CaioT

Reputation: 2211

You should be able to check 'exists' within each object returned from the query. Here is a test I just ran:

db = firestore.client()

query = db.collection(u'projects').where(u'name', u'==', 'myname').limit(1).get()

for doc in query:
    if doc.exists:
        print("Document found")

Upvotes: 1

Related Questions