2

I have this firebase document, and I want to order by the text field from the first element of the name array, so the official name.

enter image description here

Here is the code I am trying to use, but it's not working:

get(collectionName: string): Observable<T[]> {
    return this.afs.collection(collectionName, ref => {
      let query: CollectionReference | Query = ref;
      query = query.orderBy('text', 'asc').where('name', 'array-contains', 'official');
      return query;
    }).valueChanges() as Observable<T[]>;
}
4
  • Did you enabled the indexing for that specific query ? Commented May 24, 2021 at 16:01
  • Cause as I can see you are using commpund queries here (multiple queries in your case 2 queries and that is, orderBy and where) Commented May 24, 2021 at 16:02
  • To be more specific, your query is getting you the expected result and not ordering or simply not getting any results? I ask this because I believe the query you are trying to make is not possible with Firestore. Commented May 25, 2021 at 12:08
  • I don't get any results, and I don't even know if I need the where. All I want to do is order by the name[0].text Commented May 26, 2021 at 8:25

1 Answer 1

1

Querying and sorting by object values inside arrays is not possible with Firestore, at least not directly, as you can see in this community answer:

The array-contains operations checks if an array contains a specific (complete) value. It can't check if an array of objects, contains an item with a specific value for a property.

The same applies to orderBy. So in order to do that you are going to need to change your Firestore structure, a possibility is to create a separate non array field that holds the value where the query should be sorted/queryied by, you can also create a subcollection to represent the values of the array, but that is for you to decide depending on your structure.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.