0

Of course, I can know how to get the number of docs by the following code:

handledocsNumber(){
   Future<QuerySnapshot<Map<String, dynamic>>>  number =   FirebaseFirestore.instance.collection("users").get();
   number.then((value) {
   int docsNumber =  value.docs.length;
   });
    
  }

But it sounds horrifying way if the collection has huge docs because .get() will consider the whole docs as new reads special if this method was continuously for User's purposes. I just imagine docs were 100.000, that's mean .get() will always read 100.000 docs as new read every time the user need to know the length.

any good way to know the length by only paying for one query process which is the length process?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Mohammed Hamdan
  • 1,006
  • 5
  • 23

1 Answers1

1

(2022-10-20) Edit:

Starting from now, counting the documents in a collection or the documents that are returned by a query is actually possible without the need for keeping a counter. So you can count the documents using the new [count()][1] method which:

Returns a query that counts the documents in the result set of this query.

This new feature was announced at this year's Firebase summit. Keep in mind that this feature doesn't read the actual documents. So according to the [official documentation][2]:

For aggregation queries such as count(), you are charged one document read for each batch of up to 1000 index entries matched by the query. For aggregation queries that match 0 index entries, there is a minimum charge of one document read.

For example, count() operations that match between 0 and 1000 index entries are billed for one document read. For A count() operation that matches 1500 index entries, you are billed 2 document reads.


any good way to know the length by only paying for one query process which is the length process?

Yes, you can keep a counter in a document and increment the value once you add a new document to a collection. If you delete a document then simply decrement it. In this way, you can read the counter with a single document read.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • i thought about this , but will not be good way in case there no internet access with users .. if i made increment to the field in cases no internet for twice so there will be two increment process once internet get back instead of online mode which is one increment only as wanted – Mohammed Hamdan Jan 10 '22 at 13:31
  • If you create two new documents in a collection while offline, then two increment operations will be performed. When you come back online, all operations that were performed while offline, while added to Firebase servers. No worries. – Alex Mamo Jan 10 '22 at 13:43