37

I have been using Firebase Real Time Fatabase for a while and I come across Cloud Firestore today. I can't figure out on how to use LIKE operator on Firestore.

Firebase Real Time Database

ref.child('user').orderByChild('name').startAt(name).endAt(name+'\uf8ff')

On Cloud Firestore, I have tried

userRef.where('name', '>=', name); <br>
userRef.where('name', '<=', name);

But it doesn't work.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Manjok
  • 381
  • 1
  • 3
  • 6

5 Answers5

37

To solve this, you need to change orderByChild function with orderBy. So please use the following code:

ref.collection('user').orderBy('name').startAt(name).endAt(name+'\uf8ff')
Joan P.
  • 2,368
  • 6
  • 30
  • 63
  • 2
    this doesn't work when the app requires another order By for pagination purpose along with .startAfter() and .endBefore(). we cant expect that while using this trick, we have to deactivate the pagination functionality which is not right. – Elmira Behzad Jul 09 '20 at 00:13
6

There isn't an equivalent to LIKE, but you can do prefix filtering in the same way you do it in RTDB.

The query you have written is the same as equals. You need to do the same end by trick and do just less than <.

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
  • 2
    See also advice given here: https://stackoverflow.com/questions/46568142/google-firestore-query-field-contains-on-where-method . In short, you can partially emulate this if you segment the words you might be searching for ahead of time. – Gil Gilbert Oct 10 '17 at 20:33
3

FYI: With the later versions of cloud firestore (e.g. 0.12.5), the startAt() and endAt() methods require a list of strings, not a single string.

kevinH
  • 91
  • 3
3

Update for Firebase version 9

import { query, collection, getDocs, orderBy, startAt, endAt } from "firebase/firestore";

//db is exported from your firebase.js file

const ref = collection(db, "user");

const q = query(ref, orderBy('name'), startAt(name), endAt(name+'\uf8ff'));

const querySnapshot = await getDocs(q);

querySnapshot.forEach((doc) => {
    console.log(doc.id, " => ", doc.data());
});
Luca Angioloni
  • 2,243
  • 2
  • 19
  • 28
Walter Amador
  • 31
  • 1
  • 1
2

There's no such operator, allowed ones are ==, <, <=, >, >=. Here you can find all the limitations of queries in cloud firestore: https://firebase.google.com/docs/firestore/query-data/queries

etrupja
  • 2,710
  • 6
  • 22
  • 37