Skip to content
Advertisement

incrementing a field in firestore (php)

I am looking for a way to increment a field in firestore like in this documentation.

shard_ref.update("count", firebase.firestore.FieldValue.increment(1));

The only caveat is that I am trying to use firestore Client Sdk or the Admin Sdk for php.

What is a clean solution for incrementing a field in php. Does it require both read and write operations or is it possible with only write operation?

Advertisement

Answer

Firestore Client Sdk has the ability to increment a field. (use negative values to decrement). You can use it in the following way to update the field with $field_name:

$data = [
            [
                   'path' => $field_name,
                   'value' => GoogleCloudFirestoreFieldValue::increment($increment_value);
            ]
        ];     
$doc_ref->update($data);

If you are using a batching you call it as follows

$data[$field_name] = GoogleCloudFirestoreFieldValue::increment($increment_value);
$batch->add_to_batch('update', $doc_ref, $data);

Here is additional reference

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement