从cockaroachdb中的jsonb阵列删除元素
我有JSONB 标签的字段:[{“ value”:“ tag1”}]
我需要做类似此类的事情更新table1 set table tabs = tags = tags -'{“ value”:“ tag1 “}'
- 但这不起作用,
我应该执行什么查询以从数组中删除元素?
I got field with jsonb tags: [{"value": "tag1"}]
I need to do something like this update table1 set tags = tags - '{"value": "tag1"}'
- but this don't work
What query should I execute to delete element from array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您的桌子看起来
可以使用以下语句来执行此操作:
如果漫长的话,这里的实际JSON操作很简单。我们正在嵌套以下功能:
棘手的是
JSON_ARRAY_ELEMENTS
在set
更新
语句的一部分中不允许使用,因此我们可以't只是做set hash = jsonb_set(hash,array ['tags'],<该函数链>
。相反,我的解决方案在允许的位置使用,然后插入Select语句中使用它选择回到表中的结果。字符串操纵,但这很脆弱,因为您需要担心嵌套在JSON中的对象中的逗号。
Assuming your table looks like
you can do this with the following statement:
The actual json operation here is straightforward, if longwinded. We're nesting the following functions:
What's tricky is that
json_array_elements
isn't allowed in theSET
part of anUPDATE
statement, so we can't just doSET hash = jsonb_set(hash, array['tags'], <that function chain>
. Instead, my solution uses it in a SELECT statement, where it is allowed, then inserts the result of the select back into the table. Every attempted insert will hit the ON CONFLICT clause, so we get to do thatUPDATE set
using the already-computed json array.Another approach here could be to use string manipulation, but that's fragile as you need to worry about commas appearing inside objects nested in your json.
您可以使用
JSON_REMOVE_PATH
通过通过整数静态地知道元素的索引,以删除该元素。否则,我们可以做一个更简单的子查询来过滤数组元素,然后
json_agg
构建一个新数组。然后,我们可以删除具有
{“ value”:“ tag1”}
的标签:You can use
json_remove_path
to remove the element if you know its index statically by passing an integer.Otherwise, we can do a simpler subquery to filter array elements and then
json_agg
to build a new array.Then we can remove the tag which has
{"value": "tag1"}
like: