0

How to search for documents where a field starts with some term?

Example: finding all documents in someCollection where someField starts with "foo" So fields with "foo", "food", "fools" would be returned but "fop", "fopp" would not.

Alex.F
  • 5,648
  • 3
  • 39
  • 63

2 Answers2

1

Try this,

Stream streamQuery;
streamQuery = firestore.collection('someCollection')
  .where('someField', isGreaterThanOrEqualTo: searchKey)
  .where('someField', isLessThan: searchKey +'z')
  .snapshots();
Kavin-K
  • 1,948
  • 3
  • 17
  • 48
  • This works for most cases but it has a couple of limitations though. The first it only serves the english charset. Secondly, there are relevant charechters after 'z' like `~` or `{` which would not be returned. – Alex.F Nov 17 '20 at 09:37
0

This is a dart adaptation of a java answer

final strFrontCode = term.substring(0, term.length - 1);
final strEndCode = term.characters.last;
final limit =
  strFrontCode + String.fromCharCode(strEndCode.codeUnitAt(0) + 1);

final snap = await FirebaseFirestore.instance
  .collection('someCollection')
  .where('someField', isGreaterThanOrEqualTo: term)
  .where('someField', isLessThan: limit)
  .get();
Alex.F
  • 5,648
  • 3
  • 39
  • 63