Searching within collection collectionGroup query

So I came across this answer which allows limiting the collectionGroup query to a specific document: CollectionGroupQuery but limit search to subcollections under a particular document

However I also want to further filter results based on a specific field using where, which required an index. The query works without errors but it always returns empty snapshot:

const cityRef = firebase.firestore().doc('cities/cityId');

  .where('name', '>=', keywords),
  .where('name', '<=', keywords + 'uf8ff')
  .endAt(cityRef.path + "uf8ff")
  .then((querySnapshot) => {
    console.log("Found " + querySnapshot.size + " docs");
    querySnapshot.forEach((doc) => console.log("> " + doc.ref.path))
  .catch((err) => {
    console.error("Failed to execute query", err);


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

firebaser here

The problem is almost certainly that your query has range checks on two different fields (name and the document path), which isn’t possible in Firestore’s query model. As the documentation on query limitations says:

In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons must all filter on the same field.

Your startAt and endAt clauses are just different ways of writing > and < as far as this limitation is concerned.

To understand why the SDK allow you to write this query, but doesn’t give you the result you want, we’ll have to dive a bit deeper into it, so… 👇

What is possible, is to pass all relevant fields to startAt and endAt so that it can determine the correct slice across all those field values.

Doing that would also remove the need to even have the where, so it’d be:

  .startAt(keywords, cityRef.path),
  .endAt(keywords + 'uf8ff', cityRef.path + "uf8ff")

But this query now first looks for the documents starting at keywords and then if necessary for cityRef.path in there to disambiguate between multiple results.

What you want is the equivalent of this query:

const docId = firebase.firestore.FieldPath.documentId()l
  .where('name', '>=', keywords),
  .where('name', '<=', keywords + 'uf8ff')
  .where(docId, '>=', cityRef.path),
  .where(docId, '<=', cityRef.path + 'uf8ff')

Now it’s immediately clear why this isn’t possible, because we have range conditions on two fields.

I’ve been trying to get that working in this jsbin (,console), so far without success, but I’ll post back if I get it working or have a final verdict on why it doesn’t work.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x