How do I modify fields inside the new PostgreSQL JSON datatype?

前端 未结 21 1972
孤独总比滥情好
孤独总比滥情好 2020-11-22 15:37

With postgresql 9.3 I can SELECT specific fields of a JSON data type, but how do you modify them using UPDATE? I can\'t find any examples of this in the postgresql documenta

21条回答
  •  失恋的感觉
    2020-11-22 16:33

    If your field type is of json the following will work for you.

    UPDATE 
    table_name
    SET field_name = field_name::jsonb - 'key' || '{"key":new_val}' 
    WHERE field_name->>'key' = 'old_value'.
    

    Operator '-' delete key/value pair or string element from left operand. Key/value pairs are matched based on their key value.

    Operator '||' concatenate two jsonb values into a new jsonb value.

    Since these are jsonb operators you just need to typecast to::jsonb

    More info : JSON Functions and Operators

    You can read my note here

提交回复
热议问题