Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase firestore collection count with angularFire 2

I want to get the total number of the documents that exist in firestore. I don't want to get the data only the total number of inside Products collection I have 200.000 items is that possible with Angular 4-5, not angular.js

Can someone expert tell me how I can achieve that ??

My code so far and is not work

  get_total_messages() {
    this.messages_collection = this.afs.collection<MessageEntity>('messages');
    return this.messages_collection.snapshotChanges();
  }

End this is how I try to get the data but is not what I want;

this.firebase_Service.get_total_messages().subscribe( data => {
   console.log(data);
});
like image 436
George C. Avatar asked Dec 13 '22 19:12

George C.


1 Answers

There is no API to get the count of the number of documents in a Firestore collection. This means that the only ways to get the count are:

  1. Get all documents and count them client-side.
  2. Store the count as a separate property and update that as you add/remove documents.

Both approaches are quite common in NoSQL databases, with the second of course being a lot more efficient as the number of documents grows.

Firebase provides a sample of using Cloud Functions to keep a counter. While this sample is written for the Firebase Realtime Database, it can easily be modified to work on Cloud Firestore too.

Firestore also provides documentation on running aggregation queries and running distributed counters. Both seem slightly more involved than the first sample I linked though.

like image 51
Frank van Puffelen Avatar answered Jan 20 '23 10:01

Frank van Puffelen