Jump to Content
Data Analytics

Querying flexibly in Firestore with OR operator

June 30, 2023
Nick Chittle

Software Engineer

Ehsan Nasiri

Software Engineer

You can now query Firestore using the OR operator. Your application may often need to compare one or more fields with two or more values and select the documents that match at least one of the values. This is an extension to the IN operator which could be used to compare multiple values with the same field. 

For example, if you're searching for information about cats and dogs, you could use the OR operator to combine the two search terms into a single query:

‘cats = black OR dogs = brown’

This would return results that include information about both black cats and brown dogs.

Firestore now supports OR queries via server and client SDKs, with streaming and offline compatibility.

Use Cases

Support for OR operator now enables you to utilize Firestore for building applications which need to filter one or more fields with two or more values using any of our existing query constructs. 

Examples 

Let’s say you are running an employee management portal on Firestore and you want the ability to filter on a number of criteria like Title, Organization, Location, Tenure etc., you can now easily utilize OR to be able to do it.

Loading...

Now, say you want to query for performance reviews for a given employee that occurred within the last two years, or where the given rating was higher than 4. 

You can nest multiple ORs to accomplish such queries as follows :

Loading...

Nested ORs can be useful when you need to check multiple conditions, but they can also be difficult to read and understand. It is important to use them sparingly and to only use them when necessary.

OR operator can also be used on all our existing query constructs like querying across Collection Groups, or in combination with existing operators like COUNT(). 

Let’s take an example of Collection Groups called Landmarks, you can now use OR operator to filter collections within the group

Loading...

We know how valuable COUNT() is to you, now you have the ability to combine it with OR to query the data more easily as shown below :

Loading...

Extended limits for IN and array contains any  

Excitement continues, use multiple IN operators and also combine up to 30 clauses using an IN or array-contains-any operator in Firestore. 

Example :

Loading...

Note : Not_IN operator cannot be combined with the OR operator or have more than 10 clauses.

Next Steps 

Enjoy building apps more quickly and conveniently with Firestore.

Please refer to official documentation for more detailed information.

Posted in