Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Firestore - Dynamic Querying

I have a Collection in Cloud Firestore that has a certain number of items, let's call it Collection "X". This number of items will constantly be changing. At any given time, I want to listen for the number of items in this Collection and create several whereEqualto() calls on a Query object that is based on another 'Collection', let's call it "Y":

Query queryStore = FirebaseFirestore.getInstance()
            .collection("Y")
            .whereEqualTo(USER_ID_LABEL,  "item 1 from X")
            .whereEqualTo(USER_ID_LABEL,  "item 2 from X")
            .whereEqualTo(USER_ID_LABEL,  "item 3 from X");
            //Could be more than 3, could be less than 3, constantly changing

Essentially, the number of whereEqualTo() will be dynamic.

Is this type of query possible?

like image 918
tccpg288 Avatar asked May 05 '18 01:05

tccpg288


People also ask

Can you use SQL in firestore?

Cloud Firestore is a NoSQL, document-oriented database. Unlike a SQL database, there are no tables or rows. Instead, you store data in documents, which are organized into collections.

Does firestore use Websockets?

Firestore is using websockets under the hood to react to changes, plus all the optimization based on lessons learned after the original firebase realtime db, it will scale! This is just a simple example and would require some restructuring and designing, but the ideas presented can and will scale.

Is firestore slower than Realtime Database?

Cloud Firestore also features richer, faster queries and scales further than the Realtime Database. Realtime Database is Firebase's original database. It's an efficient, low-latency solution for mobile apps that require synced states across clients in realtime.

What is onSnapshot in Firebase?

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.


1 Answers

Yes. whereEqualTo() returns a Query object, which can be used to build up the final query you need. There's no obligation to chain the methods all at once, as you've demonstrated in your question. What you've written is equivalent to this:

Query queryStore = FirebaseFirestore.getInstance().collection("Y")
queryStore = queryStore.whereEqualTo(USER_ID_LABEL,  "item 1 from X");
queryStore = queryStore.whereEqualTo(USER_ID_LABEL,  "item 2 from X");
queryStore = queryStore.whereEqualTo(USER_ID_LABEL,  "item 3 from X");
like image 71
Doug Stevenson Avatar answered Sep 30 '22 07:09

Doug Stevenson