Search code examples
sqldatabasepostgresqlpostgresql-9.4jsonb

In PostgreSQL, what's the best way to select an object from a JSONB array?


Right now, I have an an array that I'm able to select off a table.

[{"_id": 1, "count: 3},{"_id": 2, "count: 14},{"_id": 3, "count: 5}]

From this, I only need the count for a particular _id. For example, I need the count for

_id: 3

I've read the documentation but I haven't been able to figure out the correct way to get the object.


Solution

  • WITH test_array(data) AS ( VALUES
      ('[
         {"_id": 1, "count": 3},
         {"_id": 2, "count": 14},
         {"_id": 3, "count": 5}
         ]'::JSONB)
    )
    SELECT val->>'count' AS result
    FROM
      test_array ta,
      jsonb_array_elements(ta.data) val
    WHERE val @> '{"_id":3}'::JSONB;
    

    Result:

     result 
    --------
     5
    (1 row)