Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push a JSON object to a array in jsonb column in postgresql

I m new in using jsonb in postgresql.

I have a following structure 

      [
          {
              "Id":1,
              "Name":"Emilia"
          },
          {
              "Id":2,
              "Name":"sophia"
          },
          {
              "Id":3,
              "Name":"Anna"
          },
          {
              "Id":4,
              "Name":"Marjoe"
          }
      ]
  1. This structure is stored in jsonb column (items).I need to append {"Id":5,"Name":"Linquin"} in this array.and set it back to jsonb column items.

I need something like this.

     [
          {
              "Id":1,
              "Name":"Emilia"
          },
          {
              "Id":2,
              "Name":"sophia"
          },
          {
              "Id":3,
              "Name":"Anna"
          },
          {
              "Id":4,
              "Name":"Marjoe"
          },
          {
              "Id":5,
              "Name":"Linquin"
          }
      ]
  1. And please let me know any way to delete objects based on id....

Appreciate any help.Thanks...

like image 543
Rajesh kumar Avatar asked Mar 09 '23 04:03

Rajesh kumar


1 Answers

Use the concatenation operator || to append an element to an array:

UPDATE s101
SET j = j || '{"Id":5,"Name":"Linquin"}'::jsonb
WHERE id = 1;
like image 163
Sandip Mavani Avatar answered Apr 25 '23 15:04

Sandip Mavani