Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing OR in firestore query - Firebase firestore

I am trying implement logical OR operator in firestore query.

db.collection('users').where('company_id', '==', companyId)                           .where('role', '==', 'Maker')                           .where('role', '==', 'Checker')                           .where('role', '==', 'Approver')                           .get().then(function(adminsSnapshot){                //Some processing on dataSnapshot }) 

But this is not the right way to implement OR.

I want all users with roles of 'Maker, Checker or Approver'.

How would i implement OR in firestore query ? There's nothing in Doc.

like image 641
Noman Ali Avatar asked Oct 30 '17 14:10

Noman Ali


People also ask

How do I get data from firestore query?

How to get query data using firebase firestore? Simply, use a get() call! query. get().

What does onSnapshot do?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

How do I use Startbafter in firebase?

Use the startAt() or startAfter() methods to define the start point for a query. The startAt() method includes the start point, while the startAfter() method excludes it. For example, if you use startAt(A) in a query, it returns the entire alphabet. If you use startAfter(A) instead, it returns B-Z .


2 Answers

Edit (November 2019) Cloud Firestore now supports "IN" queries (announcement) which allows you to do a type of OR queries that look for documents with one of a few values on the same field.

For example for the query above:

db.collection('users')   .where('company_id', '==', companyId)   .where('role', 'in', ['Maker', 'Checker', 'Approver']); 

Original answer

There is no "OR" query in Cloud Firestore. If you want to achieve this in a single query you will need a single field like maker_or_checker_or_approver: true.

Of course you can always do three queries and join them on the client.

like image 160
Sam Stern Avatar answered Sep 27 '22 20:09

Sam Stern


This is now being made possible in Firestore by newly-added support for both the in and array-contains-any operators, which allow querying for up to 10 values in a single query.

https://firebase.googleblog.com/2019/11/cloud-firestore-now-supports-in-queries.html

So, using your example, the query would look something like this.

db.collection('users')     .where('company_id', '==', companyId)     .where('role', 'in', ['Maker', 'Checker', 'Approver']); 

In the above example substitute in for array-contains-any if your data is stored in an array.

like image 34
cokeman19 Avatar answered Sep 27 '22 20:09

cokeman19