如何表达如果是else mongodb聚合?
假设我们有一个文档结构的集合,
{
"full": <string>,
"first": <string>,
"last": <string>
}
在$ project
中以下逻辑中寻找表达式
if ("$full" is null or absent)
concatenate ("$first", "_" , "$last")
else
"$full"
,我已经设法编写了此内容,但是它在某些情况下无法正常工作,并且看起来很巨大,
$project: {
"fullName": {
$cond: {
if: { "$full": null },
then: { $concat: [ "$first", "_", "$last" ] },
else: "$full"
}
}
}
什么是简洁的在MongoDB聚合中表达这种意图的方法?
Say we have a collection with this document structure
{
"full": <string>,
"first": <string>,
"last": <string>
}
Looking for an expression in $project
with the following logic
if ("$full" is null or absent)
concatenate ("$first", "_" , "$last")
else
"$full"
I have managed to write this, but it does not work properly for some cases and looks huge
$project: {
"fullName": {
$cond: {
if: { "$full": null },
then: { $concat: [ "$first", "_", "$last" ] },
else: "$full"
}
}
}
What is a concise way to express this intention in MongoDB aggregation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
$ ifnull
,因为您可以看到在这里
You can use
$ifNull
As you can see here
我认为您可以使用
$ switch
作为的替代方法,如果
, else 和然后
。这将有助于编写一系列案例。您可以在此链接中查看此演示工作代码: https://mongopoplay.net/p/num2drknbdy
I think you can use
$switch
as an alternative toif
,else
andthen
. It will help to write series of cases.You can check out this demo working code in this link: https://mongoplayground.net/p/nUM2DRkNbdY