Firestore query documents startsWith a string

Bishwajyoti Roy picture Bishwajyoti Roy · Oct 4, 2017 · Viewed 13.9k times · Source

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.

Answer

Gil Gilbert picture Gil Gilbert · Oct 4, 2017

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.