How can we update the part of existing document with jsonarray?

I tried with upsert,but I didn’t understood the usage of upsert.
Initially inserted a document.Now I want to update the document with jsonarray using php.
I want to update the empty array with jsonarray programmatically.
Can any one help me in this context?

Upsert means “update or insert”, and it operates on document as a whole. If you need to update only part of the document, you need to use subdocument API. For example, if you have travel-sample bucket loaded:

<?php
$cluster = new CouchbaseCluster('couchbase://192.168.1.194');
$bucket = $cluster->openBucket('travel-sample');

function report($hotel)
{
    printf("Hotel \"%s\" has %d public likes. First rating for Service is %d\n",
           $hotel->name, count($hotel->public_likes), $hotel->reviews[0]->ratings->Service);
}

report($bucket->get('hotel_10025')->value);

$bucket->mutateIn('hotel_10025')
    ->replace('name', 'Medway Adult Hostel')
    ->arrayAppend('public_likes', 'John Doe')
    ->remove('reviews[0]')
    ->execute();

report($bucket->get('hotel_10025')->value);

It outputs

Hotel "Medway Youth Hostel" has 8 public likes. First rating for Service is 5
Hotel "Medway Adult Hostel" has 9 public likes. First rating for Service is 3
1 Like

Humm… You could also update a part of document with upsert, or i’m wrong ?

private function flatArray(array $values, string $keyPrefix = ''): array
{
    $data = [];
    foreach ($values as $key => $value) {
        if (is_array($value) === false) {
            $data[$keyPrefix . $key] = $value;
            continue;
        }

        $data = array_replace($data, $this->flatArray($value, $keyPrefix . $key . '.'));
    }

    return $data;
}

public function update(string $id, array $values)
{
    $data = $this->flatArray($values);

    /** @var CouchbaseMutateInBuilder $couchbaseMutateInBuilder */
    $couchbaseMutateInBuilder = $this->bucket->mutateIn($id);

    foreach ($data as $key => $value) {
        $couchbaseMutateInBuilder
            ->upsert($key, $value);
    }

    $couchbaseMutateInBuilder
        ->execute();
}
1 Like

you didn’t say that you are using upsert() from subdocument API in the first message, but yes, you can use it to update document