Add an integer to an aggregate cell. This type of write makes an AddToCell API request.

## Explore further


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

- [Write examples](https://docs.cloud.google.com/bigtable/docs/writing-data)

## Code sample

### Go


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"

    	"cloud.google.com/go/bigtable"
    )

    func writeAggregate(w io.Writer, projectID, instanceID string, tableName string) error {
    	// projectID := "my-project-id"
    	// instanceID := "my-instance-id"
    	// tableName := "mobile-time-series"

    	ctx := context.Background()
    	client, err := bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Client_NewClient(ctx, projectID, instanceID)
    	if err != nil {
    		return fmt.Errorf("bigtable.NewClient: %w", err)
    	}
    	defer client.Close()
    	tbl := client.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Client_Open(tableName)
    	columnFamilyName := "view_count"
    	viewTimestamp, err := time.Parse(time.RFC3339, "2024-03-13T12:41:34Z")
    	if err != nil {
    		return err
    	}
    	hourlyBucket := viewTimestamp.Truncate(time.Hour)

    	mut := bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Mutation_NewMutation()
    	mut.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Mutation_AddIntToCell(columnFamilyName, "views", bigtable.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/bigtable/latest/index.html#cloud_google_com_go_bigtable_Timestamp_Time(hourlyBucket), 1)

    	rowKey := "page#index.html"
    	if err := tbl.Apply(ctx, rowKey, mut); err != nil {
    		return fmt.Errorf("Apply: %w", err)
    	}

    	fmt.Fprintf(w, "Successfully wrote row: %s\n", rowKey)
    	return nil
    }

### Java


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    import com.google.cloud.bigtable.data.v2.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html;
    import com.google.cloud.bigtable.data.v2.models.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.RowMutation.html;
    import com.google.common.primitives.Longs;
    import com.google.protobuf.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html;
    import java.time.Instant;
    import java.time.temporal.ChronoUnit;

    public class WriteAggregate {
      private static final String COUNT_COLUMN_FAMILY_NAME = "view_count";
      private static final long MICROS_PER_MILLI = 1000;

      public static void writeAggregate(String projectId, String instanceId, String tableId) {
        // String projectId = "my-project-id";
        // String instanceId = "my-instance-id";
        // String tableId = "page-view-counter";

        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html dataClient = https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html.create(projectId, instanceId)) {

          String rowKey = "page#index.html";
          Instant viewTimestamp = Instant.parse("2024-03-13T12:41:34.123Z");

          // Bucket the views for an hour into a single count, giving us an hourly view count for a
          // given page.
          Instant hourlyBucket = viewTimestamp.truncatedTo(ChronoUnit.HOURS);
          long hourlyBucketMicros = hourlyBucket.toEpochMilli() * MICROS_PER_MILLI;

          https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.RowMutation.html rowMutation =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.RowMutation.html.create(tableId, rowKey)
                  .addToCell(COUNT_COLUMN_FAMILY_NAME, "views", hourlyBucketMicros, 1);

          dataClient.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html#com_google_cloud_bigtable_data_v2_BigtableDataClient_mutateRow_com_google_cloud_bigtable_data_v2_models_RowMutation_(rowMutation);
          System.out.printf("Successfully wrote row %s", rowKey);

        } catch (Exception e) {
          System.out.println("Error during WriteAggregate: \n" + e.toString());
        }
      }

      public static void mergeAggregate(String projectId, String instanceId, String tableId) {
        // String projectId = "my-project-id";
        // String instanceId = "my-instance-id";
        // String tableId = "page-view-counter";

        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html dataClient = https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html.create(projectId, instanceId)) {

          String rowKey = "page#index.html";
          Instant viewTimestamp = Instant.parse("2024-03-13T12:41:34.123Z");

          // Bucket the views for an hour into a single count, giving us an hourly view count for a
          // given page.
          Instant hourlyBucket = viewTimestamp.truncatedTo(ChronoUnit.HOURS);
          long hourlyBucketMicros = hourlyBucket.toEpochMilli() * MICROS_PER_MILLI;

          https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.RowMutation.html rowMutation =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.models.RowMutation.html.create(tableId, rowKey)
                  .mergeToCell(
                      COUNT_COLUMN_FAMILY_NAME,
                      "views",
                      hourlyBucketMicros,
                      https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.ByteString.html#com_google_protobuf_ByteString_copyFrom_byte___(Longs.toByteArray(1L)));

          dataClient.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigtable/latest/com.google.cloud.bigtable.data.v2.BigtableDataClient.html#com_google_cloud_bigtable_data_v2_BigtableDataClient_mutateRow_com_google_cloud_bigtable_data_v2_models_RowMutation_(rowMutation);
          System.out.printf("Successfully wrote row %s", rowKey);

        } catch (Exception e) {
          System.out.println("Error during mergeAggregate: \n" + e.toString());
        }
      }
    }

### Python


To learn how to install and use the client library for Bigtable, see
[Bigtable client libraries](https://docs.cloud.google.com/bigtable/docs/reference/libraries).


To authenticate to Bigtable, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    import time

    from google.cloud.bigtable.data import BigtableDataClient
    from google.cloud.bigtable.data.exceptions import https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.exceptions.MutationsExceptionGroup.html
    from google.cloud.bigtable.data.mutations import https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.mutations.AddToCell.html, https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.mutations.RowMutationEntry.html

    def write_aggregate(project_id, instance_id, table_id):
        """Increments a value in a Bigtable table using AddToCell mutation."""
        with BigtableDataClient(project=project_id) as client:
            with client.get_table(instance_id, table_id) as table:
                row_key = "unique_device_ids_1"
                try:
                    with table.mutations_batcher() as batcher:
                        # The AddToCell mutation increments the value of a cell.
                        # The `counters` family must be set up to be an aggregate
                        # family with an int64 input type.
                        reading = AddToCell(
                            family="counters",
                            qualifier="odometer",
                            value=32304,
                            # Convert nanoseconds to microseconds
                            timestamp_micros=time.time_ns() // 1000,
                        )
                        batcher.append(
                            RowMutationEntry(row_key.encode("utf-8"), [reading])
                        )
                except MutationsExceptionGroup as e:
                    # MutationsExceptionGroup contains a FailedMutationEntryError for
                    # each mutation that failed.
                    for sub_exception in e.https://docs.cloud.google.com/python/docs/reference/bigtable/latest/google.cloud.bigtable.data.exceptions.html:
                        failed_entry: RowMutationEntry = sub_exception.entry
                        cause: Exception = sub_exception.__cause__
                        print(
                            f"Failed mutation for row {failed_entry.row_key!r} with error: {cause!r}"
                        )

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=bigtable).