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[]>;
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
iwannalearn
  • 51
  • 1
  • 6

1 Answers1

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.

Ralemos
  • 5,571
  • 2
  • 9
  • 18