4
votes

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);
});
3

3 Answers

11
votes

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.

1
votes

luckily , i've solved somehow using the code, try this, and it works well .

this.db.collection('User').valueChanges()
.subscribe( result => {
console.log(result.length);
})
0
votes

this.firebase_Service.get_total_messages().subscribe( data=>this.totalnumber=data.length); //now, you can get total number of messages