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.

5 Answers 5

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')
1
  • 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. Jul 9, 2020 at 0: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 <.

1
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.

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());
});
0
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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.