What is the best / most effective way to ensure an array has only unique values ? In my app a user can create a list of contacts and he picks them before the contact ids are saved in a doc in an array. Do i need to retrieve in my app all current contact id’s and only save those to array which are not present or is there a simple way to tell couch base to only save unique values in an array ?
You can do that in application by directly using KV
OR
Build a N1QL statement one like below
UPDATE default AS d
SET d.contatcs = ARRAY_APPEND(d.contacts, {"firstname":"xyz","lastname":"lanme", "id":1234})
WHERE NOT (ANY v IN d.contacts SATISFIES v.id = 1234 END);
OR the uniqueness is based on whole element, you can appended and de-dup using ARRAY_DISTINCT()
https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/arrayfun.html
So in my case for now its the docId which is something like mailing_list::06f60984-e936-48d7-b71d-db87072b40c9
now if i use the query like this
Update Contacts
USE KEYS "mailing_list::06f60984-e936-48d7-b71d-db87072b40c9"
set test = ARRAY_DISTINCT(["apples","bananas","grapes","oranges","apples","mangoes","bananas"])
it will create the the array with only the unique items. But the next time i want to add “peach” it seems to i have to retrieve all items and add them to the new elements before issuing the query since i would otherwise end up only with peach in array. How can i use append and dedup via Array Distinct ?
UPDATE Contacts USE KEYS "mailing_list::06f60984-e936-48d7-b71d-db87072b40c9"
SET test = ARRAY_DISTINCT(ARRAY_APPEND(IFMISSINGORNULL(test,[]),"apples","bananas","grapes","oranges","apples","mangoes","bananas"));
UPDATE Contacts USE KEYS "mailing_list::06f60984-e936-48d7-b71d-db87072b40c9"
SET test = ARRAY_DISTINCT(ARRAY_APPEND(IFMISSINGORNULL(test,[]),"peach"));