0

I'm working on a Firestore paginated query. Therefore, I would like to return the total number of results, so I can calculate the total number of pages and show a proper page navigation element.

You'll see from the docs below that they recommend you to use the last document on the queryResult to get the next page using startAfter(lastDoc). That's ok.

But how can I know the total number of results? Let's say I have 10.000 results in that query.

If I do:

const q = query(collection(db, "cities"), orderBy("population")); // WITHOUT THE limit
const querySnapshot = await getDocs(q);
const total = querySnapshot.docs.length; // I CAN READ THE TOTAL HERE

By querying the whole thing, I'm already paying for the 10.000 reads, right? Even though my user might only want to see the 1st page with 50 results, for example.

Is there a way to know the size/total of a query result, without paying for all the reads?

From Firestore docs:

enter image description here

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • You can store total number of entities somewhere else in the database and keep incrementing/decrementing that when required. – Dharmaraj Feb 16 '22 at 06:57
  • @Dharmaraj thanks! Yeah, I saw that idea too. Sure, it's possible, but I guess we would be going into a lot of trouble to implement that. For now, I'll stick to infinite scrolling queries, without page number navigation. – cbdeveloper Feb 16 '22 at 07:05

1 Answers1

0

Apparently this is not possible.

If you query the whole thing to know the total, you are paying for all those reads. That's a fact.

Just re-watched their official tutorial video about pagination, and there's a bunch of people in the comments complaining exactly about the lack of this feature.

You could set up Cloud Functions (with Firestore triggers) to keep track of your query sizes if you know the filters (where clause) your are going to use, but that should be cumbersome for sure.

If you are going that route, you might also just go ahead and set up a full-blown search service like ElasticSearch, Algolia or something.

Their official tutorial video on Firestore pagination:

https://www.youtube.com/watch?v=poqTHxtDXwU

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336