Home > database >  Count A Specific Field In Firestore With JavaScript
Count A Specific Field In Firestore With JavaScript

Time:10-05

I have a collection called users and one of the fields inside of the document has a string type called valid which the value can either be yes or no.

I am trying to create a query to show the number of documents where the valid field == yes and then show the total number. The following code I have just output yes yes to the console which is correct but I want it to show 2 to indicate there are 2 results.

db.collection('users').where('valid', '==', 'yes').get().then(snapshot => {

    snapshot.docs.forEach(doc => {

        console.log(doc.data().valid);
    });
});

CodePudding user response:

QuerySnapshot class contains a field called size which returns:

The number of documents in the QuerySnapshot.

So in your code, that would simply be:

db.collection('users').where('valid', '==', 'yes').get().then(snapshot => {
    console.log(snap.size);
});

The result of this code will be:

2

But please note that will work for a small collection of documents. I wrote an article called:

Where I have explained a few alternative practices that can help you achieve the same thing, in a less expensive way.

  • Related