Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of documents firestore on flutter?

I want to calculate how many documents are in a collection, not the length of the document. I have tried it with some code but what appears is the length of the character from my document name.

enter image description here

this my code :

StreamSubscription<DocumentSnapshot> userpost;
    final DocumentReference documentReference =
        Firestore.instance.document("product/$documentPost");
    userpost = documentReference.snapshots().listen((datasnapshot) {
      if (datasnapshot.exists) {
        for (int i = 0; i < datasnapshot.data.length; i++){
           print(datasnapshot.data.length);
        }
like image 908
UnderdoX Avatar asked Oct 24 '25 16:10

UnderdoX


2 Answers

You can use the count() function which was added in cloud_firestore version 4.0.0

Accepted answer might be a bad solution because you have to fetch all the documents just to count the number of documents. As per Firestore pricing, every document read is taken as 1 read count.

So a better solution is to use the count() function instead.

AggregateQuerySnapshot query = FirebaseFirestore.instance.collection('random_collection').count().get();

int numberOfDocuments = query.count;

count() is an Aggregation Query

PS: You might need to update your firebase plugins in pubspec.yaml.

like image 50
NullByte08 Avatar answered Oct 26 '25 07:10

NullByte08


An Example Function to fetch Documents Count.

void countDocuments() async {
    QuerySnapshot _myDoc = await Firestore.instance.collection('product').getDocuments();
    List<DocumentSnapshot> _myDocCount = _myDoc.documents;
    print(_myDocCount.length);  // Count of Documents in Collection
}
like image 25
anmol.majhail Avatar answered Oct 26 '25 07:10

anmol.majhail