按值删除jsonb数组元素

前端之家收集整理的这篇文章主要介绍了按值删除jsonb数组元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我确实弄清楚如何从一个数组中删除单个记录的值,但是如何为其中许多记录删除它.问题在于我如何使用子查询.因为它必须只返回单个元素.也许我的方法是错的.
  1.  
  2. Given input: '{attributes:['is_new','is_old']}'
  3. Expected result '{attributes: ['is_old']}' #remove 'is_new' from jsonb array
  4.  
  1.  
  2. Real example:
  3. # sku | properties
  4. # -------+--------------------------------
  5. # nu3_1 | { +
  6. # | "name": "silly_hodgkin",+
  7. # | "type": "food",+
  8. # | "attributes": [ +
  9. # | "is_gluten_free",+
  10. # | "is_lactose_free",+
  11. # | "is_new" +
  12. # | ] +
  13. # | }
  14.  
  1.  
  2. #Query that removes single array element:
  3.  
  4. SELECT c.sku,jsonb_agg(el) FROM
  5. catalog c JOIN (select sku,jsonb_array_elements_text(properties->'attributes') as el from catalog) c2 ON c.sku=c2.sku where el 'is_new'
  6. GROUP BY c.sku;
  7.  
  1. #Update query that removes single array element in single record
  2.  
  3. UPDATE catalog SET properties=jsonb_set(properties,'{attributes}',(
  4. SELECT jsonb_agg(el) FROM
  5. catalog c JOIN (select sku,jsonb_array_elements_text(properties->'attributes') as el from catalog) c2 ON c.sku=c2.sku
  6. WHERE el 'is_new' AND c.sku='nu3_1'
  7. GROUP BY c.sku
  8. )
  9. ) WHERE sku='nu3_1';

问题是.如何为许多数据库记录的值删除jsonb数组元素?

解决方法

使用 jsonb_set() and the delete operator -
  1. update catalog
  2. set properties =
  3. jsonb_set(properties,(properties->'attributes') - 'is_new');

Test it in rextester.

猜你在找的JavaScript相关文章