Created
January 9, 2025 23:20
-
-
Save ValchanOficial/8840067e273e5eb92793b35a6e546c7d to your computer and use it in GitHub Desktop.
[Postgres][jsonb_insert][jsonb_array_elements][with ordinality arr] objects + arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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