Skip to content

Instantly share code, notes, and snippets.

@JoeArmani
Last active January 17, 2024 14:20
Show Gist options
  • Save JoeArmani/4a292f59beb9358bdc2d1c43ad4f8fb1 to your computer and use it in GitHub Desktop.
Save JoeArmani/4a292f59beb9358bdc2d1c43ad4f8fb1 to your computer and use it in GitHub Desktop.
Using Firestore's Count Aggregator
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();
@JoeArmani
Copy link
Author

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:

shippedBoxesCountSnapshot AggregateQuerySnapshot {
  _query: AggregateQuery {
    _query: Query {
      _firestore: [Firestore],
      _queryOptions: [QueryOptions],
      _serializer: [Serializer],
      _allowUndefined: false
    },
    _aggregates: { count: {} }
  },
  _readTime: Timestamp { _seconds: 1705436310, _nanoseconds: 352328000 },
  _data: { count: 122 }
}

Returned count:

count: 122

@anthonypetersen
Copy link

awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment