Querying Postgres 9.6 JSONB array of objects

后端 未结 2 2456
隐瞒了意图╮
隐瞒了意图╮ 2021-02-20 17:56

I have the following table:

CREATE TABLE trip
(
    id SERIAL PRIMARY KEY ,
    gps_data_json jsonb NOT NULL
);

The JSON in gps_data_json conta

相关标签:
2条回答
  • 2021-02-20 18:47

    The problem arises because ->> operator cannot walk through array:

    • First unnest your json array using json_array_elements function;
    • Then use the operator for filtering.

    Following query does the trick:

    WITH 
    A AS (
    SELECT
        Id
       ,jsonb_array_elements(gps_data_json) AS point
    FROM trip
    )
    SELECT *
    FROM A
    WHERE (point->>'mode') = 'WALK';
    
    0 讨论(0)
  • 2021-02-20 19:00

    Unnesting the array works fine, if you only want the objects containing the values queried. The following checks for containment and returns the full JSONB:

    SELECT * FROM trip
    WHERE gps_data_json @> '[{"mode": "WALK"}]';
    

    See also Postgresql query array of objects in JSONB field

    0 讨论(0)
提交回复
热议问题