Update object if key exists


#1

Hi Have a document like below

{
“type”: “aud”,
“config”: {
“key1”: “value”,
“key2”: “value2”,
“key3”: “value3”
}
}

need to update multiple keys in config
{“key1”:“othervalue”,“key2”:“othervalue2”}

If the key exists the only need to update.


#2
UPDATE default AS d
SET d.config.key1 = CASE WHEN d.config.key1 IS NOT MISSING THEN "othervalue1" ELSE MISSING END,
    d.config.key2 = CASE WHEN d.config.key2 IS NOT MISSING THEN "othervalue2" ELSE MISSING END
WHERE d.config.key1 IS NOT MISSING OR d.config.key2 IS NOT MISSING ;

#3

Thank you for the reply. My config object is dynamic and its not with constant keys as below . So i cant hard code the key values. could you please provide query in dynamic way

{
“type”: “aud”,
“config”: {
“key1”: “value”,
“key2”: “value2”,
“key3”: “value3”
.
.
.
.
}
}

and the input also dynamic as below
{“key1”:“othervalue”,“key2”:“othervalue2”,…}


#4

Update if present else add

UPDATE default AS d
SET d.config = OBJECT_CONCAT(IFMISSINGORNULL(d.config,{}),{"key1": "value1", "key2": "value2", "key3": "value3"})
WHERE d.type = "aud";

Update only key present

UPDATE default AS d
SET d.config = OBJECT_CONCAT(d.config,
                         OBJECT o.name:o.val FOR o IN OBJECT_PARIS({"key1":"othervalue1","key4":"value4","key3":"value3"})
                         WHEN d.config.[o.name] IS NOT MISSING END)
WHERE d.type = "aud"
        AND  ANY v IN  OBJECT_NAMES({"key1": "othervalue1", "key4": "value4", "key3": "value3"}) SATISFIES
                   d.config.[v] IS NOT MISSING END;

#5

This query in adding the keys even not exists in actual config. My requirements is update keys values if exits but don’t add any new keys

My record
{
“type”: “aud”,
“config”: {
“key1”: “value”,
“key2”: “value2”,
“key3”: “value3”
}
}

and values planning to update are key1 and key2 and passing input as {“key1”: “value10”, “key2”: “value20”, “otherKeys”: “value30”}

Output should be

{
“type”: “aud”,
“config”: {
“key1”: “value10”,
“key2”: “value20”,
“key3”: “value3”
}
}


#6
UPDATE default AS d
SET d.config = OBJECT_CONCAT(d.config,
                         OBJECT o.name:o.val FOR o IN OBJECT_PARIS({"key1":"othervalue1","key4":"value4","key3":"value3"})
                         WHEN d.config.[o.name] IS NOT MISSING END)
WHERE d.type = "aud"
        AND  ANY v IN  OBJECT_NAMES({"key1": "othervalue1", "key4": "value4", "key3": "value3"}) SATISFIES
                   d.config.[v] IS NOT MISSING END;