0

Is there any way to make queries on a jsonb field in some table in Postgres that are basically equitable to the Mongodb query operators (listed here https://docs.mongodb.org/manual/reference/operator/query-comparison/)

I would like to be able to store some json objects in a postgres table for example:

{"power": 200},
{"power": 400},
{"power": 0},
{"power": 146297},

If I do the current method of

SELECT * FROM mytable where json_field ->> 'power' < '2';

I get retured both the row for power 0 and power 146297...

Is there some documentation somewhere that specifies how to do

gt, gte, lt, lte, eq, not equal, in array, not in array

3
  • Postgres 1.4? Seriously? Commented Jan 26, 2016 at 0:50
  • jsonb supported from 9.4, it must be a typo (but please update your question to be sure). Commented Jan 26, 2016 at 9:25
  • Yeah type - should be 9.4 Commented Jan 26, 2016 at 11:57

2 Answers 2

2

You need to cast ->> string result values:

WITH mytable(json_field) AS ( VALUES
  ('{"power": 200}'::JSONB),
  ('{"power": 400}'::JSONB),
  ('{"power": 0}'::JSONB),
  ('{"power": 146297}'::JSONB)
)
SELECT * FROM mytable where (json_field->>'power')::INTEGER < 2;

Result is:

  json_field  
--------------
 {"power": 0}
(1 row)
Sign up to request clarification or add additional context in comments.

Comments

1

The documentation is on the postgresql page. The documentation states that the ->> operator returns string, your right hand operand is a string too so the result is correct.

To do what you wanted to do you must cast the result returned from the json to integer:

SELECT * FROM mytable where (json_field ->> 'power')::int < '2';

Please note the brackets are needed as not to case 'power' to int.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.