Firebase firestore collection count with angularFire 2
Asked Answered
W

4

5

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);
});
Woodley answered 19/11, 2017 at 16:5 Comment(0)
H
10

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.

Happy answered 19/11, 2017 at 16:12 Comment(0)
P
0
this.firebase_Service.get_total_messages().subscribe(data => this.totalnumber = data.length);

Now you can get total number of messages

Peppel answered 5/12, 2017 at 7:54 Comment(1)
Ganza the @Frank above says there is no way to count the collection docks If I use your way I need to download 200.000 docks that 200Mb of data you need 3 weeks to download all that and if you want to count all that the RAm is gonna explode. Thank you but this is not what I want. Welcome to stackoverflow . GanzaWoodley
T
0

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);
})
Thebes answered 8/4, 2020 at 16:57 Comment(1)
This is not the best approach as if we have 1000 documents and we need just count, Here firebase pricing calculates as 1000 documents.Hawaiian
G
0

well there's a way, but it uses Firebase JS SDK instead

code mostly got from: Getting an error on Firestore's getCountFromServer()

const collectionRef = collection(
  this.afs.firestore,
  `${this.getRoleDBPath()}`
);
console.log(
  await getCountFromServer(
    query(collectionRef, where('email', '==', '[email protected]'))
  )
);
Gravimeter answered 7/8, 2024 at 16:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.