I am wondering if there is a simple way to access the certain fields in my json do stored in couchbase via php. I know i can get the whole doc and then via json try to extract the info but lets say this is a large doc and i only want data of one or 2 fields in the doc, is there a way to just access them or even better just retrieve an array of certain fields from that doc ?
It is easy to do with subdocument API. I will post here an example from LookupInBuilder API docs
<?php
$cluster = new \Couchbase\Cluster("couchbase://localhost");
$bucket = $cluster->openBucket('default');
$bucket->upsert('foo', ['path1' => 'value1']);
$result = $bucket->lookupIn('foo')
->get('path1')
->exists('path2')
->execute();
var_dump(count($result->value)); //=> int(2)
var_dump($result->value[0]['code']); //=> int(0) COUCHBASE_SUCCESS
var_dump($result->value[0]['value']); //=> string(6) "value1"
var_dump($result->value[1]['code']); //=> int(63) COUCHBASE_SUBDOC_PATH_ENOENT
var_dump($result->value[1]['value']); //=> NULL
Note that by calling get()
on the builder multiple tiimes you will be able to access multiple paths in the document at once.
Thanks that works like a charm, but not to sound to greedy is there a way to access any value like
path1 directly if i got the whole doc ? Or is this only avail if i query individual fields ? Also what would be the best way if there would be multiple path1’s in the doc ?
thanks for quick insight
Accessing multiple paths in the document using lookup builder does not involve receiving whole document body if you asking about it.
BTW there is a shortcut for that:
$bucket->retrieveIn('docId', 'path1', 'path2', 'path3');
Or you are looking for path API on the document objects, which were received using $bucket->get()
? In this case, no, it is not available, because the path is evaluated on the server side.