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
Conditional grouping with $exists inside $cond
提问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 $project
ing 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
回答by Imran
回答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是不需要的。我把它放在那里……只是为了好玩。我认为它目前对查询的影响不大。稍后我将测试速度。