简体   繁体   English

使用 Postgres 更新嵌套 JSON 中的查询删除数据

[英]Updated query in nested JSON with Postgres removes data

I have this JSON doc我有这个 JSON 文档

    {
  "name": "Perry Street Brasserie",
  "cuisine": "French",
  "stars": 0.3,
  "address": {
    "street": "959 Iveno Square",
    "city": "Fokemlid",
    "state": "AL",
    "zipcode": "18882"
  },
  "reviews": [
    {
      "person": {
        "_id": {
          "$oid": "57d7a121fa937f710a7d486e"
        },
        "address": {
          "city": "Burgessborough",
          "street": "83248 Woods Extension",
          "zip": "47201"
        },
        "birthday": {
          "$date": "2011-03-17T11:21:36Z"
        },
        "email": "murillobrian@cox.net",
        "first_name": "Yvonne",
        "job": "Counselling psychologist",
        "last_name": "Pham"
      },
      "comment": "Aliquam est reiciendis alias neque ad.",
      "created_on": {
        "$date": "2018-02-01T01:56:29.627Z"
      }
    }

I need to change the first_name value but my queries simply remove data related to that name.我需要更改 first_name 值,但我的查询只是删除了与该名称相关的数据。 So, my queries get executed successfully but end up removing data instead of updating it.因此,我的查询成功执行,但最终删除数据而不是更新数据。

I tried the following two queries and both give me the same results我尝试了以下两个查询,都给了我相同的结果

   UPDATE restaurants
SET info = jsonb_set('{"reviews":["person"]}', '{"first_name"}', '"Vedat"', true)
WHERE info ->'reviews'-> 0 -> 'person' ->> 'first_name' = 'John'


UPDATE restaurants
SET info = info::jsonb - 'first_name' || '{"reviews":[{"person": {"first_name":"Vedat"}}]}'
WHERE info::json->'reviews'-> 0 -> 'person' ->> 'first_name' = 'Jenna'

You aren't passing in the whole column as the first value, and you need to provide a path to the value you want to change in the form of an array:您没有将整列作为第一个值传递,您需要以数组的形式提供要更改的值的路径:

For example:例如:

UPDATE restaurants
SET info = jsonb_set(info, '{reviews,0,person,first_name}', '"Vedat"', true)
WHERE info->'reviews'->0->'person'->>'first_name' = 'John';

So you effectively have to pass the whole JSON document to jsonb_set, and it will return the modified document.因此,您实际上必须将整个 JSON 文档传递给 jsonb_set,它将返回修改后的文档。

Regards问候

Thom汤姆

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

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