【问题标题】:How to update a json array using the key如何使用密钥更新 json 数组
【发布时间】:2019-10-22 17:12:20
【问题描述】:

假设我的 jsonb 列中有这个 json

{
  "fields": [
    {
      "name": "firstName",
      "age": 17
    },
    {
      "name": "lastName",
      "age": 25
    },
    ...
}

如何在不使用索引的情况下只更新“firstName”?

到目前为止我有这个,但这是使用我不想使用的索引

UPDATE person
SET 
    field = jsonb_set(field, 
    concat('{fields, 0, name'}')::text[], 
    'new value'::jsonb, 
    TRUE)

【问题讨论】:

  • 显示表结构?
  • “我目前有这个,但这是使用我不想使用的索引” 但是你可以尝试SET enable_seqscan = ON; SET enable_indexscan = OFF; SET enable_indexonlyscan = OFF; ... 手册中提到的@ 987654321@

标签: sql json postgresql


【解决方案1】:

您需要取消嵌套数组元素,替换您想要的元素,然后将它们聚合回来:

update the_table tg
   set data = data||(select jsonb_build_object(
                                 'fields', jsonb_agg(case
                                                       when t.j ->> 'name' = 'firstName' 
                                                         then t.j||'{"name": "new_name"}'
                                                       else t.j
                                                     end))
                     from jsonb_array_elements(tg.data -> 'fields') as t(j))
where ....;

在线示例:https://rextester.com/BZVKD68215

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2020-07-19
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多