繁体   English   中英

如何更新 Postgres JSON 字段中对象数组中存在的对象的特定值

[英]How to update a specific value of a object present in array of object within Postgres JSON Field

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

{
    "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"
        }
    ]
}

例如,他的名字是Devang to Dev使用 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来更新 user_name 但JSON_SET只接受。 它将更新上层,而不是嵌套层

在嵌套元素更新的情况下,使用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;
  

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM