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
  • 112,184
  • 14
  • 139
  • 167
Jack
  • 295
  • 7

1 Answers1

1

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
  • 112,184
  • 14
  • 139
  • 167
  • 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 – Jack 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