Using N1ql to update an array element only when it exists


I want to update an element in an array doc.fields[] when the element’s name is “field1”. I want the update statement to run only when such element exists. I try to put a WHERE clause to guard it but Couchbase complains “syntax error - at WHERE”. If I remove the where clause then it would overwrite the last element if no element’s name is “field1” because ARRAY_POSITION returns -1, which is not what I want.

Is there any other way to perform such operation?

UPDATE doc USE KEYS "document1"
SET fields[ARRAY_POSITION(fields[].name, “field1”)] = {“name”:“field2”},
].name, “field1”) > 0

I think I can use collection operator instead.

Yes, collection operators.

Also see UPDATE SET … FOR … END syntax.

1 Like