Firebase Firestore order by most items in array using array-contains-any

Viewed 162

Is there a way to use array-contains-any and order the query by the items contained in the array? I know it can be done once the array is retrieved, but I'm planning to use pagination so I can retrieve thousands of documents by page.

1 Answers

Firestore can only filter on values that exist in the document. It can't perform calculations to get the value to filter on, as the value needs to exist in the index.

If you want to filter on the number of items that exist in an array field, you can add an additional field that keeps that count and then update that field whenever you update the array itself. Once you have this additional field, you can easily use it in query conditions.

If you want to order on the number of values in the array that were matched by the query, that is not possible in a query. You'll have to perform that sorting in your application after the query has returned its results.

Related