Getting a Firestore document while using shards

Stay organized with collections Save and categorize content based on your preferences.

Getting a Firestore document while using shards

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


// getCount returns a total count across all shards.
func (c *Counter) getCount(ctx context.Context, docRef *firestore.DocumentRef) (int64, error) {
	var total int64
	shards := docRef.Collection("shards").Documents(ctx)
	for {
		doc, err := shards.Next()
		if err == iterator.Done {
		if err != nil {
			return 0, fmt.Errorf("Next: %v", err)

		vTotal := doc.Data()["Count"]
		shardCount, ok := vTotal.(int64)
		if !ok {
			return 0, fmt.Errorf("firestore: invalid dataType %T, want int64", vTotal)
		total += shardCount
	return total, nil


async function getCount(docRef) {
  const querySnapshot = await docRef.collection('shards').get();
  const documents =;

  let count = 0;
  for (const doc of documents) {
    count += doc.get('count');
  return count;


$result = 0;
$docCollection = $db->collection('samples/php/distributedCounters')->documents();
foreach ($docCollection as $doc) {
    $result += $doc->data()['Cnt'];


def get_count(self, doc_ref):
    """Return a total count across all shards."""
    total = 0
    shards = doc_ref.collection("shards").list_documents()
    for shard in shards:
        total += shard.get().to_dict().get("count", 0)
    return total


# project_id = "Your Google Cloud Project ID"
# collection_path = "shards"

require "google/cloud/firestore"

firestore = project_id: project_id

shards_ref = firestore.col_group collection_path

count = 0
shards_ref.get do |doc_ref|
  count += doc_ref[:count]

puts "Count value is #{count}."

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.