Last active
January 17, 2024 14:20
-
-
Save JoeArmani/4a292f59beb9358bdc2d1c43ad4f8fb1 to your computer and use it in GitHub Desktop.
Using Firestore's Count Aggregator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const countDocs = async () => { | |
try { | |
const shippedBoxesCountSnapshot = await db.collection('boxes') | |
.where('145971562', '==', 353358909) | |
.where('789843387', '==', 13) | |
.count() | |
.get(); | |
console.log('shippedBoxesCountSnapshot', shippedBoxesCountSnapshot); | |
console.log('count:', shippedBoxesCountSnapshot.data().count); | |
} catch (error) { | |
console.error("Error updating boxes collection: ", error); | |
} | |
} | |
countDocs(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why use
.count()
:(1) This is like submitting a Firestore query for .length that returns only the count of documents satisfying the query (not the underlying data).
(2) It is extremely light on data use & data in transit. Instead of returning all data in all docs, it just returns the doc count.
(3) It is billed at 1 read per 1000 documents counted instead of one read per fetched document -> very efficient for billing.
Returned snapshot:
Returned count: