QBoard » Supporting Tech Stack » Cloud » Cloud Firestore collection count

Cloud Firestore collection count

  • Is it possible to count how many items a collection has using the new Firebase database, Cloud Firestore?

    If so, how do I do that?

      July 26, 2021 3:46 PM IST
    0
  • Simplest way to do so is to read the size of a "querySnapshot".

    db.collection("cities").get().then(function(querySnapshot) {      
        console.log(querySnapshot.size); 
    });

     

    You can also read the length of the docs array inside "querySnapshot".

    querySnapshot.docs.length;
    

     

    Or if a "querySnapshot" is empty by reading the empty value, which will return a boolean value.

    querySnapshot.empty;
      July 26, 2021 3:51 PM IST
    0
  • As far as I know there is no build-in solution for this and it is only possible in the node sdk right now. If you have a
    db.collection('someCollection')
    you can use
    .select([fields])
    to define which field you want to select. If you do an empty select() you will just get an array of document references.
    example:
    db.collection('someCollection').select().get().then( (snapshot) => console.log(snapshot.docs.length) );
    This solution is only a optimization for the worst case of downloading all documents and does not scale on large collections!
     
      August 21, 2021 5:43 PM IST
    0