本文介绍了$ cond中有$ exists的条件分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个键A和B,并且它们在文档中的存在是互斥的.我必须在A存在时按A分组,而在B存在时按B分组.因此,我将所需的值$project放入一个名为MyKey的计算键中,在该键上将执行$group.但似乎我在语法上犯了一个错误.我尝试通过两种方式编写$ project:

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:

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

{$project: {MyKey: {$cond: [{$exists: ["$A", 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 } ...

怎么了?

推荐答案

使用 $ifNull 而不是$project中的$cond:

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

如果A存在,但不存在,则将使用其值;否则,将使用B的值.

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

这篇关于$ cond中有$ exists的条件分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!