Search code examples
couchbasesql++

Updating sub document map in n1q1 query CB


Here is my document in CB,

{
    "users": {
        "11111": "ACTIVE",
        "22222": "ACTIVE",
        "33333": "ACTIVE",
        "44444": "ACTIVE",
        "55555": "ACTIVE",
        "666666": "ACTIVE",
        "777777": "ACTIVE",
        "888888": "ACTIVE"
    }
}

I want to update all keys of this users map to 0 instead of active.

output expected

{
    "users": {
        "11111": 0,
        "22222": 0,
        "33333": 0,
        "44444": 0,
        "55555": 0,
        "666666": 0,
        "777777": 0,
        "888888": 0
    }
}

I tried this

UPDATE bucketname SET x=0 FOR x in bucketname.users END WHERE meta().id='%documentKey%'


Solution

  • UPDATE mybucket AS b
    SET b.users = OBJECT n:0 FOR n:v IN b.users END
    WHERE ......
    

    Construct new object and and set the value

    FOR n:v IN b.users END
       iterates each field of b.users (n holds name, v holds value)
    
    OBJECT n:0  
       Construct new object field name from n and value is 0 constant