Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ValchanOficial/8840067e273e5eb92793b35a6e546c7d to your computer and use it in GitHub Desktop.
Save ValchanOficial/8840067e273e5eb92793b35a6e546c7d to your computer and use it in GitHub Desktop.
[Postgres][jsonb_insert][jsonb_array_elements][with ordinality arr] objects + arrays
-- INFO: array starts with 0 and position starts with 1
-- INFO: Get position from pathArray1 element that type is group
WITH position AS(SELECT position
FROM my_table, jsonb_array_elements(data->'path1'->'pathArray1') with ordinality arr(elem, position)
WHERE id = 2 AND elem->>'type' = 'group')
-- INFO: Insert new value into pathArray1[position].path2.pathArray2
UPDATE my_table
SET data = jsonb_insert(
data,
'{path1, pathArray1}' || array[CAST((SELECT * FROM position) - 1 AS text)] || '{path2, pathArray2, 1}',
'"valchan was here"'
)
WHERE id = 2;
SELECT * FROM my_table WHERE id = 2;
{"path1": {
"pathArray1": [
{"type": "group", "path2": {"pathArray2": ["valchan was here"]}},
{"type": "solo", "path2": {"pathArray2": []}}
]
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment