$cond 中存在 $的条件分组

我有两个关键字 A 和 B,它们在文档中的存在是相互排斥的。当 A 存在时,我必须按 A 分组,当 B 存在时,我必须按 B 分组。因此,我正在将所需的值 $project0放入一个名为 MyKey 的计算键中,并在其上执行 $group。但是看起来我在语法上犯了一个错误。我尝试用两种方法写 $project:

{ $project: { MyKey: { $cond: [{ $vis: [“ $A”,true ]} ,“ $A”,“ $B”]}}}

还有

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

但我一直得到这个错误:

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

怎么了?

64503 次浏览

Use $ifNull instead of $cond in your $project:

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

If A exists and is not null its value will be used; otherwise the value of B is used.

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.status parameter, to check that if it exists inside the cond.

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

$or is 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.

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

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

and truth table for $not is as

enter image description here

Hopes that Helps

You can simulate exists with

$ne : [$var_to_check, undefined]

This returns true if the var is defined

Some sharing that i found in $cond and check is existing:

$cond: {
if: "$A1",
then: "$A1",
else: "$B1"
}