【问题标题】:How to update a specific value of a object present in array of object within Postgres JSON Field如何更新 Postgres JSON 字段中对象数组中存在的对象的特定值
【发布时间】:2021-10-06 03:07:57
【问题描述】:

这是我的 JSON 字段值。它存储在 PostgreSQL 表中。我想在user 键中搜索和更新特定的user_name

{
    "user": [
        {
            "user_name": "Devang",
            "user_weight": 0.7676846955248864
        },
        {
            "user_name": "Meet",
            "user_weight": 0.07447325861051013
        },
        {
            "user_name": "L.b.vasoya",
            "user_weight": 0.056163873153859706
        }
    ],
    "address": [
        {
            "address_name": "India"
        }
    ]
}

谁的名字是DevangDev 使用 Django JSONField 例如

 "user": [
        {
            "user_name": "Dev",
            "user_weight": 0.7676846955248864
        },
....

我已尝试使用 RAWQuery 进行查找。这是查询。

select json_field->user from user_table where json_field @> '{"user": [{"user_name": "Devang"}]}';

它会像这样返回

        {
            "user_name": "Devang",
            "user_weight": 0.7676846955248864
        },
        {
            "user_name": "Meet",
            "user_weight": 0.07447325861051013
        },
        {
            "user_name": "L.b.vasoya",
            "user_weight": 0.056163873153859706
        }
]

我也尝试过 JSON_SET 来更新用户名,但 JSON_SET 只接受。它将更新上层,而不是嵌套层

【问题讨论】:

标签: python sql json django postgresql


【解决方案1】:

在嵌套元素更新的情况下,使用 JSONB_SET 有点棘手。如果要先设置嵌套元素的值,则需要获取要更新的元素的确切路径。请尝试以下查询:

with cte as (
  select  id,  ('{user,'||index-1||',user_name}')::text[] as json_path
  from user_table, jsonb_array_elements(json_field->'user') 
  with ordinality arr(vals,index) where arr.vals->>'user_name' ='Devang' --put the value to be replaced
  )
 update user_table 
set json_field = jsonb_set(json_field,cte.json_path,'"Dev"',false) --put the new value in '""' here
 from cte where user_table.id=cte.id;
  

DEMO

【讨论】:

  • 感谢您的回答,我有另一个问题,请检查一次。这里第二条记录中的dbfiddle.uk/… 有两个 Devang 用户名它只会更新一次我应该怎么做才能更改所有匹配的用户名
猜你喜欢
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多