Ask Your Question
4

How to query an array of objects with JSONB in Postgres?

asked 2021-11-07 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-08-23 15:00:00 +0000

huitzilopochtli gravatar image

To query an array of objects with JSONB in Postgres, you can use the JSONB functions and operators. Here are some examples:

  1. Filter by a specific field in the objects:
SELECT *
FROM mytable
WHERE data->'myarray' @> '[{"field": "value"}]';

This query selects all rows from the mytable table where the myarray field is an array of objects that contain a field with the value value.

  1. Filter by multiple fields in the objects:
SELECT *
FROM mytable
WHERE data->'myarray' @> '[{"field1": "value1", "field2": "value2"}]';

This query selects all rows from the mytable table where the myarray field is an array of objects that contain both fields with the values value1 and value2.

  1. Filter by a specific value in the objects:
SELECT *
FROM mytable
WHERE EXISTS (
  SELECT 1
  FROM jsonb_array_elements(data->'myarray') obj
  WHERE obj->>'field' = 'value'
);

This query selects all rows from the mytable table where the myarray field is an array that contains at least one object with a field value of value.

  1. Filter by a subquery on the objects:
SELECT *
FROM mytable
WHERE EXISTS (
  SELECT 1
  FROM jsonb_array_elements(data->'myarray') obj
  WHERE obj->>'field' = 'value'
  AND obj->>'otherfield' IN (
    SELECT field
    FROM othertable
    WHERE condition
  )
);

This query selects all rows from the mytable table where the myarray field is an array that contains at least one object with a field value of value, and where the same object also contains an otherfield value that matches a subquery on another table.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-07 11:00:00 +0000

Seen: 20 times

Last updated: Aug 23 '22