Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple elements of a list using Couchbase N1QL

context

I have somewhere in my couchbase documents, a node looking like this :

"metadata": {
    "configurations": {
        "AU": {
         "enabled": false,
         "order": 2147483647
        },
        "BE": {
         "enabled": false,
         "order": 2147483647
        },
        "BG": {
         "enabled": false,
         "order": 2147483647
        } ...
    } 
}

and it goes along with a list country unicodes and their "enabled" state

what I want to achieve

update this document to mark is as disabled ("enabled" = false) for all countries

to do this I hoped this syntax would work (let's say I'm trying to update document with id 03c53a2d-6208-4a35-b9ec-f61e74d81dab)

UPDATE `data` t 
SET country.enabled = false
FOR country IN t.metadata.configurations END
where meta(t).id = "03c53a2d-6208-4a35-b9ec-f61e74d81dab";

but it seems like it doesn't change anything on my document

any hints ? :)

thanks guys,

like image 835
jderegnaucourt Avatar asked Oct 16 '25 06:10

jderegnaucourt


1 Answers

As the filed name is dynamic you can generate field names using OBJECT_NAMES() and use that during update of field.

UPDATE data t USE KEYS "03c53a2d-6208-4a35-b9ec-f61e74d81dab" 
      SET  t.metadata.configurations.[v].enabled = false FOR v IN OBJECT_NAMES(t.metadata.configurations) END ;

In above example OBJECT_NAMES(t.metadata.configurations) generates ["AU", "BE","BG"] When field of JSON is referenced .[v] it evaluates v and value become field. So During looping construct t.metadata.configurations.[v].enabled becomes

t.metadata.configurations.`AU`.enabled, 
t.metadata.configurations.`BE`.enabled, 
t.metadata.configurations.`BG`.enabled

Depends on value of v.

like image 119
vsr Avatar answered Oct 17 '25 19:10

vsr