Sub-document array operations related doubts

I have few doubts about array operations on sub-documents,

How to append new object with existing array,
How to delete the sub-documents array at existing object.
How to add new field at all the sub-documents based on the conditions

Ex: This is our document
{
“iam”: “QW230”,
“fav_apps”: [
{
“app_id”: “9b94d625-e54e-4356-8728-9f598ca6e2f5”,
“status”:1
}
]
}

  1. I need to insert new favourite apps

“fav_apps”: [
{
“app_id”: “9b94d625-e54e-4356-8728-9f598ca6e2f5”,
“status”:1
},
{
“app_id”: “9b94d625-e54e-4356-8728-9f598ca6e2f5”,
“status”:1
}
]
2. I need to deleted sub-document like app_id as 9b94d625-e54e-4356-8728-9f598ca6e2f5,
3. How to add new field on all the sub-documents with existing values based, ex: if sub-document status key is 1 then add new key for force_update with 0, otherwise to add force_update as 1

“fav_apps”: [
{
“app_id”: “9b94d625-e54e-4356-8728-9f598ca6e2f5”,
“status”:1,
“force_update”:0
},
{
“app_id”: “9b94d625-e54e-4356-8728-9f598ca6e2f5”,
“status”:0,
“force_update”:1
}
]

Thanks,

https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/update.html
https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/arrayfun.html

@vsr1 i referred above update & arrayfun documentation, but not suitable for all the scenarios. Adding new field for sub-document is possible throw OBJECT_ADD. Please clarify first & second point for subdocument insert and delete.

Thanks

UPDATE default AS d
SET d.fav_apps =  ARRAY_APPEND(d.fav_apps , {...........})
WHERE .....;

UPDATE default AS d
SET d.fav_apps =   ARRAY v FOR v IN d.fav_apps WHEN v.app_id != "9b94d625-e54e-4356-8728-9f598ca6e2f5" END
WHERE .....;

UPDATE default AS d
SET fa.force_update  = CASE WHEN fa.status == 1 THEN  0 ELSE 1 END
                      FOR fa IN  d.fav_apps END
WHERE .....;
1 Like

Great @vsr1, Thank you