Ian Barber
Ian Barber

Reputation: 183

Count A Specific Field In Firestore With JavaScript

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

Upvotes: 0

Views: 495

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 1

(2022-10-20) Edit:

Starting from now, counting the documents in a collection or the documents that are returned by a query is actually possible without the need for keeping a counter. So you can count the documents using the new count() method which:

Returns a query that counts the documents in the result set of this query.

This new feature was announced at this year's Firebase summit. Keep in mind that this feature doesn't read the actual documents. So according to the official documentation:

For aggregation queries such as count(), you are charged one document read for each batch of up to 1000 index entries matched by the query. For aggregation queries that match 0 index entries, there is a minimum charge of one document read.

For example, count() operations that match between 0 and 1000 index entries are billed for one document read. For A count() operation that matches 1500 index entries, you are billed 2 document reads.


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.

Upvotes: 1

Related Questions