mongodb $cond 中 $exists 的条件分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14213636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:00:11  来源:igfitidea点击:

Conditional grouping with $exists inside $cond

mongodbmongodb-query

提问by Aafreen Sheikh

I have two keys A and B and their existence in the document is mutually exclusive. I have to group by A when A exists and group by B when B exists. So I am $projecting the required value into a computed key called MyKey on which I'll perform a $group. But it looks like I'm making a mistake with the syntax. I tried writing $project in two ways:

我有两个键 A 和 B,它们在文档中的存在是互斥的。当 A 存在时我必须按 A 分组,当 B 存在时我必须按 B 分组。所以我$project将所需的值输入到一个名为 MyKey 的计算键中,我将在该键上执行$group. 但看起来我在语法上犯了一个错误。我尝试以两种方式编写 $project :

{$project: {MyKey: {$cond: [{$exists: ["$A", true]}, "$A", "$B"]}}}

{$project: {MyKey: {$cond: [{$exists: ["$A", true]}, "$A", "$B"]}}}

and

{$project: {MyKey: {$cond: [{"A": {$exists:true}}, "$A", "$B"]}}}

{$project: {MyKey: {$cond: [{"A": {$exists:true}}, "$A", "$B"]}}}

But I keep getting the error:

但我不断收到错误消息:

{ "errmsg" : "exception: invalid operator '$exists'", "code" : 15999, "ok" : 0 } ...

{ "errmsg" : "exception: invalid operator '$exists'", "code" : 15999, "ok" : 0 } ...

What's going wrong?

怎么了?

回答by JohnnyHK

Use $ifNullinstead of $condin your $project:

使用$ifNull的,而不是$cond在你的$project

{ $project: {MyKey: {$ifNull: ['$A', '$B'] }}}

If Aexists and is not nullits value will be used; otherwise the value of Bis used.

如果A存在且不存在,则null使用其值;否则使用的值B

回答by Imran

if one wants to check $exists with in $cond an alternative approach is to use $not with $cond

如果想要在 $cond 中检查 $exists,另一种方法是将 $not 与 $cond 一起使用

{$project: {MyKey: {$cond: [{$not: ["$A"]}, "$B", "$A"]}}} 

and truth table for $not is as

$not 的真值表是这样的

enter image description here

在此处输入图片说明

Hopes that Helps

希望有所帮助

回答by Delcon

You can simulate exists with

你可以模拟存在

$ne : [$var_to_check, undefined]

This returns true if the var is defined

如果定义了 var,则返回 true

回答by Tudor

I found your questions while looking for a similar problem, but insted of a key, I was looking for my parameters. I finally solved the issue.

我在寻找类似问题的同时发现了您的问题,但是为了找到一个关键,我正在寻找我的参数。我终于解决了这个问题。

This is what I used for my $_id.statusparameter, to check that if it exists inside the cond.

这是我用于$_id.status参数的内容,以检查它是否存在于 cond 中。

$cond: [{
     $or: [{
          $ne: ["$_id.status", null]
     }]
}, 1, null]

$oris not needed. I keep it there... just for fun. I don't think it affects the query that much for the moment. I will test the speed later.

$or是不需要的。我把它放在那里……只是为了好玩。我认为它目前对查询的影响不大。稍后我将测试速度。