Postgres JSONB 相当于 MongoDB $ifNull(聚合)

huangapple go评论56阅读模式
英文:

Postgres JSONB equivalent to MongoDB $ifNull (aggregation)

问题

抱歉,代码部分不需要翻译,以下是翻译好的内容:

我正在使用Postgres数据库(Supabase)而不是MongoDB的过程中。抱歉,我对Postgres还相对陌生,之前只用过MongoDB。

对于某些列,仍然更倾向于使用JSONB,这是合理的。

是否有与MongoDB $ifNull (aggregation) 类似的功能,可以进行替换表达式值?

在MongoDB中,$ifNull表达式会评估输入表达式中的空值,并返回找到的第一个非空输入表达式值,如果所有输入表达式都评估为空,则返回替代表达式值。

不幸的是,在Postgres中我没有取得任何成功,在MongoDB中这非常容易。

我的MongoDB代码片段如下:

$ifNull: [
    `$$proposedamendments.name_lang.${l}`,
    "$$proposedamendments.name_lang.en",
    "$$proposedamendments.name_lang.fr",
]

非常感谢所有Postgres专家的帮助。

英文:

I am in a process of using Postgres database (Supabase) instead of MongoDB. Sorry I am still rather new to Postgres, worked only with MongoDB previously.

For some columns it is still preferable and reasonable to use JSONB.

Is there any equivalent to MongoDB $ifNull (aggregation) with replacement expression value?

In MongoDB the $ifNull expression evaluates input expressions for null values and returns the first non-null input expression value found or a replacement expression value if all input expressions evaluate to null.

Unfortunately I have zero success in Postgres, in MongoDB it was really easy.

My piece of code in MongoDB was as this:

$ifNull: [
    `$$proposedamendments.name_lang.${l}`,
    "$$proposedamendments.name_lang.en",
    "$$proposedamendments.name_lang.fr",
]

Thank very much to all Postgres experts for their help.

答案1

得分: 0

非常感谢 @ray 给的建议。
这段代码对我有效:

SELECT COALESCE(name_lang->>'${l}', name_lang->>'en', name_lang->>'fr') FROM "TABLE_NAME";

(${l} 是从客户端动态添加的)

英文:

Thank you very much @ray for the tip.
This code worked for me

SELECT COALESCE(name_lang->>'${l}', name_lang->>'en', name_lang->>'fr') FROM "TABLE_NAME";

(${l} is added dynamically from client)

huangapple
  • 本文由 发表于 2023年2月14日 08:26:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定