If USE KEYS you can skip the index. But still keep the WHERE clause so that if the document doesn’t qualify no update is done. If you remove WHERE clause it will update same document again if not qualified.
That is actually very useful information to know, as that behavior is not self-evident. So if the USE KEYS clause fails to find a document, the update query continues and updates all documents unless a “backup” WHERE clause is provided.
USE KEYS can have multiple values i.e USE KEYS [“doc1”,“doc2”,“doc3”]
If there is only “doc1”,“doc3” present (If none of is present update is done. no further processing)
WHERE clause condition is applied on “doc1”,“doc3”, If “doc3” has item.id = 456 and not "doc1"
WHERE clause eliminates “doc1” update only qualifies “doc3”
SET clause will modify the “doc3”, and update new “doc3”
If you don’t have WHERE clause “doc1” is updated as it is because SET … FOR… WHEN… END will leave the document “doc1” as it is. This is what you want to avoid unnecessary update.
Understood! Very good internals info to know about. Thanks for the explanation.
Back to my original post, your solution has worked. Im still trying to wrap my head around nested FOR looping to target specific items in nested documents.
So, for example, if I wanted to modify only the value of the “1” key, and leave the “2” key alone, how would I go about doing that using the above structure?
UPDATE default AS d USE KEYS ["k100"]
SET val.`1` = [ "New String" ]
FOR val IN item.`values`
FOR item IN d.items
WHEN item.id = 123 AND val.`1` == ["String"] END
WHERE ANY item IN d.items SATISFIES item.id = 123 END;
I want to completely replace the specific sub-document in level_2.
This is my query:
UPDATE default USE KEYS 'blah' SET
y = {"id":1, "value_1":101, "value_2":1010}
FOR y in x.level_2 FOR x IN level_1
WHEN x.`code` = "123" and y.id = 1 END
WHERE ...
You need to replace in parent to keep the value attached to document not just y otherwise it may add root of the document.
UPDATE default USE KEYS 'blah' SET
x.level_2[ARRAY_POS(x.level_2,y)] = {"id":1, "value_1":101, "value_2":1010}
FOR y in x.level_2 FOR x IN level_1
WHEN x.`code` = "123" and y.id = 1 END
WHERE ...
OR
UPDATE default USE KEYS 'blah' SET
x.level_2 = ARRAY CASE WHEN y.id = 1 THEN {"id":1, "value_1":101, "value_2":1010} ELSE y END FOR y IN x.level_2 END
FOR x IN level_1
WHEN x.`code` = "123" END
WHERE ...
Very weird that it does not work in my example, even though its the same structure as in my example. I suppose Ill dig more and see why. But even if I copy your example verbatim, it does not update the document.