postgres jsonb_set multiple keys update

后端 未结 2 1060
南笙
南笙 2020-12-05 09:21

I have DB table with jsonb column.

number  | data
    1   | {\"name\": \"firstName\", \"city\": \"toronto\", \"province\": \"ON\"}

I need a

2条回答
  •  忘掉有多难
    2020-12-05 09:52

    The documentation says:

    The || operator concatenates the elements at the top level of each of its operands. ... For example, if both operands are objects with a common key field name, the value of the field in the result will just be the value from the right hand operand.

    So using your example data:

    update table_name set
      data = data || '{"city": "ottawa", "phone": "phonenum", "prefix": "prefixedName"}'
    where number = 1;
    

    Additionally if the object you want to edit is not at the top level - just combine the concatenation and jsonb_set function. For example, if the original data looks like

    {"location": {"name": "firstName", "city": "toronto", "province": "ON"}}
    

    then

    ...
    data = jsonb_set(data, '{location}', data->'location' || '{"city": "ottawa", "phone": "phonenum", "prefix": "prefixedName"}')
    ...
    

提交回复
热议问题