Postgres 9.4 jsonb queries basic operators

耗尽温柔 提交于 2019-12-12 03:35:59

问题


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


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/35002524/postgres-9-4-jsonb-queries-basic-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!