Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore query documents startsWith a string

Is it possible to query a firestore collection to get all document that starts with a specific string?

I have gone through the documentation but do not find any suitable query for this.

like image 349
Bishwajyoti Roy Avatar asked Oct 04 '17 20:10

Bishwajyoti Roy


People also ask

Can firestore update multiple documents matching a condition using one query?

Cloud Firestore does not support the equivalent of SQL's update queries.

How do I get specific data from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.

Can you query firestore?

Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection or collection group. These queries can also be used with either get() or addSnapshotListener() , as described in Get Data and Get Realtime Updates.


2 Answers

You can but it's tricky. You need to search for documents greater than or equal to the string you want and less than a successor key.

For example, to find documents containing a field 'foo' staring with 'bar' you would query:

db.collection(c)     .where('foo', '>=', 'bar')     .where('foo', '<', 'bas'); 

This is actually a technique we use in the client implementation for scanning collections of documents matching a path. Our successor key computation is called by a scanner which is looking for all keys starting with the current user id.

like image 187
Gil Gilbert Avatar answered Sep 24 '22 17:09

Gil Gilbert


same as answered by Gil Gilbert. Just an enhancement and some sample code. use String.fromCharCode and String.charCodeAt

var strSearch = "start with text here"; var strlength = strSearch.length; var strFrontCode = strSearch.slice(0, strlength-1); var strEndCode = strSearch.slice(strlength-1, strSearch.length);  var startcode = strSearch; var endcode= strFrontCode + String.fromCharCode(strEndCode.charCodeAt(0) + 1); 

then filter code like below.

db.collection(c) .where('foo', '>=', startcode) .where('foo', '<', endcode); 

Works on any Language and any Unicode.

Warning: all search criteria in firestore is CASE SENSITIVE.

like image 33
Kyo Kurosagi Avatar answered Sep 22 '22 17:09

Kyo Kurosagi