Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a Firestore query by comparing two document's fields values

I'm having my first steps with Cloud Firestore, and I am stuck on this one. I'm looking for a where query to return me values that are >= the limit.

  [{
    'limit': 100,
    'value': 200 
  }, 
  {
    'limit': 50,
    'value: 50,
  },
  {
    'limit': 95,
    'value': 90, 
  }]

I am using the Firebase Admin Python SDK in a Cloud Function.

Any hints?

like image 342
Kubber Avatar asked Aug 02 '26 16:08

Kubber


1 Answers

As Alex has explained, there is no way to compare two document's fields values when executing a query with Firestore.

One possible approach, would be to save the result of the inequality when you save the document to the database. If, when you save a "check" document you know the two values (limit and value), you could add a third field named, for instance,valueAboveLimit with a value of True or False, that you calculate when you save the "check" document (i.e. from your front-end with the corresponding client SDK or from a server with the Firebase Admin Python SDK, depending on how you write the Firestore documents).

Then your query will be easy:

database = firestore.client()
col_checks = database.collection('checks')
query_checks = col_checks.where('valueAboveLimit', '==', True)
results = query_checks.get()

In case you don't have the values of limit and value at the time you save the Firestore document (for example the limit field is written later), you could use a Cloud Function that is triggered when the Firestore document is changed and, if the two fields are present, calculates and saves this valueAboveLimit field.

like image 185
Renaud Tarnec Avatar answered Aug 05 '26 06:08

Renaud Tarnec